A lightweight script loader

Script loaders are the Javascript blogosphere topic de jour and so I thought I’d weigh in with my own contribution. Use a script loader to delay the download and execution of portions of your page’s Javascript code, increasing page render/load performance. Script loaders originated with performance guru Steve Souders and some excellent libraries have sprung up as a result of his work.

Most script loading libraries I’ve looked quickly become over-complicated, whereas I wanted to make something ultra-light, and easy to use. Here’s a simple technique I use because the code is neat and should address 80% of requirements. It’s based on Steve’s asynchronous script loading technique, with some code added to attach a callback function once all scripts have loaded.

The script loader should be called as follows:

loadScript('script1.js', 'script2.js', function() {
  //code to run when both scripts have been loaded

The function works by placing a correctly formatted script tag into the header of the page and attaching a load handler to each script to enable the execution of a callback (if required). I like this technique because debugging tools such as Firebug continue to work as normal, respects any cache settings, but still provides the performance parallel script downloading – plus its seriously lightweight.

To create dependancy chains, use the function like so:

loadScript('script1.js', 'script2.js', function() {
  loadScript('script3.js', function() {
    //Execute code 

You can view the source code here.

A lightweight script loader

2 thoughts on “A lightweight script loader

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s