JQuery - Remove tag Script - javascript

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

Related

remove script after load in memory [duplicate]

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);

why jQuery attr('href', '#') set an empty value rather than #

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","#");

Undo jQuery or revert DOM?

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

How to dynamically add a Javascript function (and invoke)

Based on a click event on the page, via ajax I fetch a block of html and script, I am able to take the script element and append it to the head element, however WebKit based browsers are not treating it as script (ie. I cannot invoke a function declared in the appended script).
Using the Chrome Developer Tools I can see that my script node is indeed there, but it shows up differently then a script block that is not added dynamically, a non-dynamic script has a text child element and I cannot figure out a way to duplicate this for the dynamic script.
Any ideas or better ways to be doing this? The driving force is there is potentially a lot of html and script that would never be needed unless a user clicks on a particular tab, in which case the relevant content (and script) would be loaded. Thanks!
You could try using jQuery... it provides a method called .getScript that will load the JavaScript dynamically in the proper way. And it works fine in all well known browsers.
How about calling eval() on the content you receive from the server? Of course, you have to cut off the <script> and </script> parts.
If you're using a library like jQuery just use the built-in methods for doing this.
Otherwise you'd need to append it to the document rather than the head like this:
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
In all honesty, I have no idea why the script tag is cut like that, but a lot of examples do that so there's probably a good reason.
You'll also need to account for the fact that loading the script might take quite a while, so after you've appended this to the body you should set up a timer that checks if the script is loaded. This can be achieved with a simple typeof check on any global variable the script exports.
Or you could just do an eval() on the actual javascript body, but there might be some caveats.
Generally speaking though, I'd leave this kind of thing up to the browser cache and just load the javascript on the page that your tabs are on. Just try not to use any onload events, but rather call whatever initializers you need when the tab is displayed.

How to find the snippet of JavaScript that modifies an element?

The page I'm trying inspect has a hidden <input type="hidden" name="Foo" value="123 /> element on a page, where Javascript/AJAX modifies the value. I'm trying to find where on earth in Javascript is the code that modifies this value from time to time.
Is there a tool that could help me find the places in javascript that use/modify that element? Does Firebug provide this, if so, how?
Note: If tried looking for "Foo" in the code, but I haven't found any matching titles. There's JSON and Mootools loaded, +application specific code, which results several thousands lines of code. The element is probably accessed indirectly.
Firebug 1.5 will have "Break-on-Modify" on the HTML panel. See http://getfirebug.com/doc/breakpoints/demo.html#html - Break on DOM (HTML) Mutation Events.
How do you know that the javascript is modifying this value? Since it looks you already know when it's called (since you know it changes), I would suggest a breakpoint in Firebug in the first event that initiates the changing (probably an onclick attribute in other element).
It's kind of hard telling you a "generic" way of knowing where in javascript it's changing Foo's value since there are a lot of different approachs, different libraries, each one with it's syntax.
For example, if you tried searching "Foo" and didn't find it, the script may be traversing the DOM and changing the input's value as a "first child of something". I would try to search for names or ids of input's parent elements and understand the code from there.
I usually just try to understand the javascript logic from every script I use with Firebug's debugging techniques - but just on the script that uses the libraries.
If Firebug doesn't let you define breakpoints on setting some value, you could insert something like this in the page (Firefox-only):
$("textarea")[0].__defineSetter__("value", function(val) {
alert("called");
})
And either breakpoint on the function in Firebug or use console.log or whatever to dump the stack to the firebug console.
I remember seeing somewhere a presentation on Firebug plans, which included a section on various kinds of breakpoints to be supported, but I can't find a link to it right now.
[edit] The above is for the case the value is set by assigning to the value property: .value = .... If you need to catch the moment an attribute is changed (.setAttribute("value", ...)), you can use DOM mutation listeners.

Categories

Resources