Dan Hlavenka
Dan Hlavenka

Reputation: 3817

Dynamic Javascript import

I'm making a web page that needs to be able to dynamically change the JavaScript code that's running. Many times, functions in the dynamic code have the same names, but behave differently, so using document.getElementsByTagName('head')[0].appendChild(script); isn't an option. Right now, I've got <script type="text/javascript" id="dynamicScript" src="about:blank"></script> in the head of the document, and when I want to change the active script, I call document.getElementById('dynamicScript').src="ajax.php?get=script&script=" + page;, and that PHP page spits out the corrent script (without tags). It doesn't work, though. Am I doing something wrong, or is there something else I could to that would also work?

Upvotes: 0

Views: 209

Answers (2)

evasilchenko
evasilchenko

Reputation: 1870

Just because you're spitting out the correct javascript, doesn't mean that it is being executed. As Stefan has pointed out, one option is to use the getScript plugin for jQuery in order to accomplish your task.

Upvotes: 0

Benjamin Atkin
Benjamin Atkin

Reputation: 14735

You need to add a new <script> element to the DOM, not just change it. Also there's no way for you to unload your old script without reloading the page. If you need to remove functions and data that were declared by a previous script, you need to do it programmatically. Replacing functions works.

Finally I recommend using a script loader like LABjs, RequireJS, ControlJS, or SexyJS. Doing it manually is extra work.

Edit: You could also just use getScript() if you're using jQuery and don't need the extra control over what order your scripts are loaded in.

Upvotes: 1

Related Questions