Blog archives

jsDynaLoad: Dynamic Javascript loader with multi-file support

I wrote a (very) small Javascript function to dynamically load Javascript files. In modern Javascript development you usually have more than one Javascript file in your page (e.g. jQuery, a few plugins, a main javascript file) that depend on each other. Loading them using the <script> tag works, but sometimes you get a dependency problem because scripts are not guaranteed to load from top to bottom in the order they appear in on the page.

The script is based on this version by Nicholas C. Zakas but adds an extra option to load an array of Javascript files.

Fork it on Github or get a minified version.

Here’s how  you use it:

// Loading a single file
jsDynaLoad("single.js", function() {
    alert("callback after the single file");
});

// Loading an array of files
var files = ["1.js", "2.js"];
jsDynaLoad(files, function() {
    alert("callback after the array of files");
});

// A callback is not required
jsDynaLoad("nocallback.js");

To get a better performance remember to place your scripts at the bottom of your page, close to the closing </body> tag. You can also include the minified version of loadScript inline in a <script> tag to save a HTTP request.

Add a comment