How to remove JavaScript loaded dynamically using AJAX

In smaller words:

I have several sections of JavaScript located in different places in the document. Some of them are uploaded and evaluated using AJAX:

<script id="js5533" type="text/javascript"> javascript and jquery stuff (lots) </script> <script id="js7711" type="text/javascript"> javascript and jquery stuff (lots) </script> 

As you can see, I ID each section.

My goal is to get rid of a specific section by pressing a button.

 $('.somebutton').click(function() { $('#js7711').remove(); }); 

Of course, this function removes only the element from the document and all the JavaScript functions in the js7711 section still work.

I don’t want to manually remove every function and variable from a section, doing things like a (); a = 0;

Are there fewer coding solutions?

Thanks.

PS Also used jQuery.

+4
source share
4 answers

Found a lazy workaround for this.

First of all: the reason for getting rid of the previous JS code is to run a new code (similar or the same with the old one) without reloading the page.

Solution: To forget about previously downloaded code and execute your new code using jQuery.globalEval(js); where js is the var containing your actual new JS code.

jQuery just creates a different sequence with your new code, which does not interfere with the old one, excluding live events (solved with event.stopPropagation ())

Works great for me.

Like someone said: you cannot make the browser forget about the JS that has already been executed.

+3
source

Despite the fact that I find this question really strange, I will try not to go deeper and just anwser. Rewrite the imported scripts with something like this:

 window.js7711 = function() { // javascript and jquery stuff (lots) } 

Then, when you download this inconvenient thing, you should execute it js7711()

And when deleting, I assume that you are doing something like:

var myID = "js7711"

$("#" + myID).remove();

add this:

delete window[myID]

If you declare functions in this imported script, you should consider adding an array with the names of the imported functions js7711.imported = ["something", "trololo"] , and then removing them in a loop.

In any case, I think your approach / structure is a bit flawed.

+3
source

Are there fewer coding solutions?

Not.

You better think if this is really the best approach, I mean getting rid of javascript sections ...

0
source

The problem is that if you connected any events with elements outside # js7711, they would still trigger, i.e. javascript functions will still work.

The solutions that come to mind are to generate JS functions that check if their "root" element exists (ie # js7711) and are executed only if the element can still be found.

Then, if you remove # js7711, the JS functions will stop working, maybe you want to!

0
source

Source: https://habr.com/ru/post/1394799/


All Articles