In my HTML-head i have this script included:
<script id="mode" type="text/javascript" src="article.js"></script>
With a button click I’d like to change the source of the script to customers.js so that it then looks like this:
<script id="mode" type="text/javascript" src="customers.js"></script>
The point is that I don’t want the article.js to be included in my page then anymore, so I can’t just use .append().
So, click on the article button -> only article.js included, click on the customers button -> only customers.js included.
I tried to solve this with jQuery this way, but I doesn’ seem to work…:
$("#btArticle").click(function(){
$("#mode").attr("src","article.js");
});
$("#btCustomers").click(function(){
$("#mode").attr("src","customers.js");
});
Do you know where my mistake is?
Update: There are methods with the same name in customers.js and article.js. So there’s a onSave() method in both of them and when I clicked the customer button before, I want the onSave() method of customers.js to be executed, not the one in articles.js.
Once the script has been downloaded and evaluated, anything it leaves lying around will remain unless explicitly removed; they’re not linked to the
scriptelement itself and removing it won’t have any effect on them.The only way to get rid of the stuff
article.jsleaves lying around is to remove or overwrite each and every thing it creates and keeps.Concrete example:
If the
article.jslisted above is processed, you can remove thescriptelement that loaded it, and that will have no effect on thefooglobal variable or the event handler that it hooked up.If you want to have scripts that you can unload, have them use the module pattern with a single global symbol they add by assigning to a property on
window, e.g.:You can then remove it by doing this:
Re your comment on the question:
If you have global function declarations in
customers.jsthat use the same name as global function declarations inarticles.js, when you loadcustomers.js, it will replace those functions.So if you have this in
articles.js:…and this in
customers.js:And you have a button:
When you’ve loaded just
articles.jsand notcustomers.js, clicking that button gives you “Articles!”. If you then loadcustomers.js, clicking the button will give you “Customers!”.That works because the event handler calls
foo(), but the event handler itself is notfoo. Theonclickattribute creates a hidden event handler for you. The equivalent jQuery would be:Note that just doing
.click(foo)will do something very different: It will hook up the function thatfoopoints to at that moment as the event handler. Even if you change whatfoopoints to later (by loadingcustomers.js), that won’t change the fact that the old function is hooked up as a handler.FWIW, from the question and your comments, I think I’d recommend sitting back and reviewing your strategy for this page/app. All of this swapping of code in and out and such seems like a design problem.