James Starmer

Dynamic JavaScript Loading Technique

Here is the basic problem, you load a page into a container (lets say a div). You can do

div.innerHTML = responseTextFromAjax;

but if the page that comes back in the response has javascript in it the browser won’t evaluate and run that javascript. So a solution is to use prototype.js and use it’s element.update function.

div.update(responseTextFromAjax);

Element.update in turn calls it’s evalScripts function which does an eval() call on anything inside of script tags like:

<script></script>

Now what if you have a script tag that includes another (external) javascript file like:

<script src="anotherscript.js" ></script>

Then as far as I know you are out of luck if you’re using prototype.js.

Here is my solution. I wrote a class that can take the response text from an Ajax call and parses it for script tags with a src attribute (similar to the way that prototype.js evalScripts parses) then appends those script files to the current open page either with an ajax which retrieves the file or by appending it to the dom with a script element. I hope the help someone who is having the same problem that I had.

Here is the source: ScriptLoader.zip