I have some jQuery that runs on a page. As a short-term fix I want to remove the code within the tags (containing the JS), that are on the page so that this jQuery does NOT run.
Is there any way that I can do this, or stop the code from running? I want to revert back to the typical DOM state, not the manipulated one...
Edit:
I have a script tag on the page that runs some javascript.
Due to certain limitations, I can't simply remove this - I have to include a javascript file to remove this script tag / OR prevent this javascript from running.
I want to revert back to how the page should look without having been manipulated by the script tag that is already on the page.
If you can only include a javascript file, you could try re-declaring the jquery object so it can't run:
jQuery = null;
$ = null;
That would kill jQuery providing it's loaded after. This however would probably cause of lot of javascript errors. On that trail of thought, you could just plug in some broken JS and it would stop jQuery from executing if it's before the jQuery stuff.
I can't think on a scenario where it's needed.
And indeed it's impossible to revert the DOM after manipulation. reset button doesn't revert the DOM
if its in a method you can just use return false; before your code runs, you can also just comment out your code, or wrap your code in a method that never runs:
$("p").hide();
becomes:
function() {
$("p").hide();
}
Or have I misunderstood your question?
Just move your code out of the jQuery(document).ready function, that should make the HTML stay the way it was.
After reading your additions in edit, I think the only to see the page before loading that script would be to add a break-point using Firebug script console at that particular script.
Edit: Add further answer after reading the OPs edit.
the only way I can think of you achieving this without manipulating the source or dom would be to test for a cookie prior to code execution,if it does not exist then set it and continue executing the rest of your code something like this. When you want to revert changes made in the dom back to the 'original' just refresh the window and the existence of the cookie will prevent execution a second time
(function() {
if($.cookie('foo') == null) {
$.cookie('foo', 'bar');
$('#alert').click(function() {
alert('run');
});
}
})();
the only flaw I can see in this is if a user rejects the cookie in which case if it really matters I would alert the user and again break out of execution
Related
As the title says, if I remove a script tag from the DOM using:
$('#scriptid').remove();
Does the javascript itself remain in memory or is it cleaned?
Or... am I completely misunderstanding the way in which browsers treat javascript? Which is quite possible.
For those interested in my reason for asking see below:
I am moving some common javascript interactions from static script files into dynamically generated ones in PHP. Which are loaded on demand when a user requires them.
The reason for doing this is in order to move the logic serverside and and run a small script, returned from the server, clientside. Rather than have a large script which contains a huge amount of logic, clientside.
This is a similar approach to what facebook does...
Facebook talks frontend javascript
If we take a simple dialog for instance. Rather than generating the html in javascript, appending it to the dom, then using jqueryUI's dialog widget to load it, I am now doing the following.
Ajax request is made to dialog.php
Server generates html and javascript that is specific to this dialog then encodes them as JSON
JSON is returned to client.
HTML is appended to the <body> then once this is rendered, the javascript is also appended into the DOM.
The javascript is executed automatically upon insertion and the dynamic dialog opens up.
Doing this has reduced the amount of javasript on my page dramatically however I am concerned about clean up of the inserted javascript.
Obviously once the dialog has been closed it is removed from the DOM using jQuery:
$('#dialog').remove();
The javascript is appended with an ID and I also remove this from the DOM via the same method.
However, as stated above, does using jQuery's .remove() actually clean out the javascript from memory or does it simple remove the <script> element from the DOM?
If so, is there any way to clean this up?
No. Once a script is loaded, the objects and functions it defines are kept in memory. Removing a script element does not remove the objects it defines. This is in contrast to CSS files, where removing the element does remove the styles it defines. That's because the new styles can easily be reflowed. Can you imagine how hard it would be to work out what a script tag created and how to remove it?
EDIT: However, if you have a file that defines myFunction, then you add another script that redefines myFunction to something else, the new value will be kept. You can remove the old script tag if you want to keep the DOM clean, but that's all removing it does.
EDIT2: The only real way to "clean up" functions that I can think of is to have a JS file that basically calls delete window.myFunction for every possible object and function your other script files may define. For obvious reasons, this is a really bad idea.
If your scripts have already executed removing the DOM elements are not going to get rid of them. Go to any page with JavaScript, open up your preferred javascript console and type $("script").remove(). Everything keeps running.
And this demonstrates #Kolink answer:
http://jsfiddle.net/X2mk8/2/
HTML:
<div id="output"></div>
<script id="yourDynamicGeneratedScript">
function test(n) {
$output = $("#output")
$output.append("test " + n + "<br/>")
}
test(1);
</script>
Javascript:
$("script").remove();
// or $("#yourDynamicGeneratedScript").remove();
test(2);
test(3);
test(4);
function test(n) {
$output = $("#output")
$output.append("REDEFINED! " + n + "<br/>")
}
test(5);
test(6);
test(7);
I'm using jQuery version 1.8.3
jQuery('#edit_param_apppmStyleImage').attr("href","#");
The HTML turns out with
<a id="edit_param_apppmStyleImage" href="">Edit</a>
It sets an empty value rather than "#". And it is 100% surely caused by my site's special script written by others.
Any specialist can provide some suggestions about what may cause such weird behavior? Btw, it sets other values like '##' normally.
It sets an empty value rather than "#". And it is 100% surely caused
by my site's special script written by others.
You did not provide any details regarding the special script running on your site. But I'd try running the script after everything (including images) is loaded. In that case, this is what comes to my mind;
The load event is sent to an element when it and all sub-elements have
been completely loaded.
Since it's a bit different than $(document).ready() function, it could make a difference if some other script is overriding your script's intended behaviour.
Try the following
jQuery(window).bind("load", function() {
jQuery('#edit_param_apppmStyleImage').attr("href","#");
});
What we're doing here is that we're delaying the execution of the script until the entire window is loaded. And since anything in $(document).ready() function executes before the code in $(window).load() function, we are reducing the chance of your script to be overridden.
Not sure that will work, but give it a try.
Replace attr() with prop():
jQuery('#edit_param_apppmStyleImage').prop("href","#");
I need to remove two <script> tags from a page dynamically, at the document ready.
Every tag has its own id;
I've tried to insert in the code:
$("#idPrimoScript").remove();
$("#idSecondoScript").remove();
but nothing happens...
Some ideas? Thanks
As I can understand from your question, you want to remove (actually disable) the scripts included in your 2 script tags.
a work around I usually used to make in these situations is to introduce a variable which will act as a flag or a passing signal.
let's say that I will create a global variable which will be the flage I will be using:
var enableMySpecialScript = true
as you can see, I initially set the value of this flag to true, and whenever I need to disable the special script inside my page, I set this flag to false, then inside my script file, i always check for the flag's value,so when it's only "true", the script will execute, meaning that when it's false the script will not run, which is exactly what you are asking for.
This way you don't have to mess up with removing stuff or altering functions, and from my experience with this solution, it's a clean and debuggable one :)
Apparently (having not tried this myself beyond a simple proof script) the way to do this is to create another function with the same name.
See:
How to override a function in another javascript file?
JavaScript: Overriding alert()
Override jQuery functions
Overriding a function in jQuery plugin
I would like to clear the entire head section once the page loads... actually, my goal would be to delete all JavaScript code held in the head section.
Is there some way to do something like this:
document.head.innerHTML = "";
Explanation:
I am using a Python script that uses Qt and webkit to take screenshots of websits.
It works on most sties, but there is one that it fails on. That site has a bunch of JavaScript code that it runs on timeouts. The WebKit webpage object allows me to execute JavaScript on the page. If there is some way to have the JavaScript remove all of the code form the head section I'd like to be able to try that for testing purposes to see if it resolves my screenshot script issue.
You can remove elements from the head, but it wont matter. The scripts have already run and removing the elements wont unload them or anything.
document.getElementsByTagName("head")[0].innerHTML = "";
// IE
var htmlEl = document.getElementsByTagName("html")[0];
htmlEl.removeChild(document.getElementsByTagName("head")[0])
var el = document.createElement("head");
htmlEl.appendChild(el);
To stop JavaScript scripts running by setTimeout, you should use clearTimeout, but for this case you should have a handler... But you're lucky, if they are defined as global variables.
Try using:
document.getElementsByTagName('head').innerHTML = "";
to clear the head. document.head does not exist so this may not work.
But you may want to try to disable the JavaScript using JavaScript like suggested by noah.
See http://www.manticmoo.com/articles/jeff/programming/javascript/removing-javascript-with-javascript.php for directions. It sounds crazy but evidently it works.
As noah said, simply removing the code from the head tag won't accomplish anything. You have to actually undo what the code is doing. For example, if it's using setTimeout() to set up the timeout code you're complaining about, you need to use clearTimeout() to disable it.
$('#id').empty();
Worked very well.
I have html-pages with links where i want to attach a function to their onclick event. One way to do it is of course:
Save
But I know this is not the best practice. So instead I wait for window.onload, loop through the links and attach the save-function to the links with rel="save". The problem with this is that it waits until the whole page has finished loading which can be several seconds after the link is displayed and clickable.
So is there another way to do this? Avoiding onclick in the html but that makes it work immediately when the link is rendered.
Internet Explorer has a handy attribute for <script> tags called defer. It's for delaying the parsing of a script until the document has finished loading. For other browsers that support it, you can use DOMContentLoaded, as someone else suggested and for browsers that don't support either you can fall back to onload.
<script type="text/javascript" defer>
//- Run this code when the DOM parsing has completed
</script>
I did a quick Google search for "DOMContentLoaded defer" and found the following page that might help:
http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-event-for-browsers
In your case, you can just leave that as it is. Stick to the simplest possible thing, even if it is not the general best practice.
You could try DOMContentLoaded event instead of load. IE also gives you the defer attribute for script tags, which defers execution until the DOM is loaded. If those don't work for you, then you are stuck with the solutions you mention, as far as I know.
I don't know if this is appropriate for your solution, but you could insert script immediately below the are with the links you need altered. This script would not be wrapped in a function, allowing the browser to execute it immediately when seen. The effect is that you can run script before the full page is loaded, altering only the items that exist above the script being run. (If you reference something below the script, it will fail.)
BTW, this is almost certainly not a best practice, and some would probably label it a worst practice.
How about this?
Save
Note: This solution requires to users to have Javascript enabled. Not exactly best practice, but may be suitable for your scenario.
The ideal here would be to use the ideas of Unobtrusive Javascript.
In this way, if the Javascript isn't loaded the link would still do something. It's a link right, so it leads the user to another piece of content? - this should work without Javascript. And if the functionality attached to the links can ONLY work with Javascript you should create and insert them into the DOM with Javascript (they aren't clickable if they aren't there...).
(Otherwise how about delegating the click event to a wrapper element? Does that work before the element is complete?)
edit: Oh, and "save" sounds very much like it ought to be a button in a form rather than a link. The Unobtrusive JS stuff still applies though.