Jørgen Jørgen - 4 months ago 42
Javascript Question

Load javascript sequentially from javascript code

I have a javascript widget that is included in a page by inserting a single script tag (as the application should be easiliy distributable):

<script type="text/javascript" src="loadMyWidget.js"></script>

loadMyWidget.js then needs to load multiple script files, which has to run in a certain sequence. I've tried to load them async by inserting script elements into the DOM, but that doesn't give me control of the sequence.

I also tried using head.js which is great for modern browsers, but I can't get it to work in IE7 and 8.

Minifying the scripts into one file is unfortunately difficult, as it is composed of a number of files from different projects and I wouldn't know when to update the script.

As simple as it seems, I need to load javascript files from javascript code in a certain sequence and get it to work in all browsers, including IE7 and 8.


I have run into this exact same issue and handled it with:

document.write('<script type="text/javascript" src="other1.js"></script>');
document.write('<script type="text/javascript" src="other2.js"></script>');


The code will be loaded and run synchronously. Pros: simple, light, cross browser compliant, no deps. Cons: ugly.

More details: http://stackoverflow.com/a/3292763/235179