Problem

In the common case, scripts block other portions of the page from downloading. Downloading these scripts asynchronously has a number of advantages related to actual and perceived page load time, but this technique makes handling dependencies difficult. Ideally, we want to be able to run a specific block of code as soon as the external script it requires has loaded, without having to modify the external script.

For instance, a number of sites use Google Analytics for metrics. The code snippet Google provides downloads an external script and runs a few lines of code once that script is loaded, but it does so using a document.write call that delays the onload event.

Solution

Wait until the page loads (window.onload) to start downloading the external script in the background, using the script DOM element approach. We optionally use setTimeout() to avoid triggering the browser loading indicators. Attach the dependent code to the onload event (or browser equivalent) of the newly created script element.

View source to see the code. (It comes to about 600 characters if you minify it).

This has been tested and works in Safari 4.0 Mac, Safari 3.2 Win, IE 6.0, Firefox 3.0.4 Mac/Win, Firefox 2 Mac, Opera 9.62 Mac/Win.

Demo 1 – runs automatically when window.onload event fires

  1. Wait for the window.onload event to fire (all images loaded)…
  2. Start downloading external script A (6 second load time)…
  3. Start downloading external script B (3 second load time)…
  4. Wait for script A to complete download…
  5. Wait for script B to complete download…
  6. Check that each of those scripts has set the sleep_now global variable (this is our dependency):
    A.
    B.

Demo 2 – loading scripts asynchronously on-demand

 

Example Usage

postLoadJS("http://www.example.com/js/external.js", function() {
    // code to run on load
});

Slow-loading image to delay window.onload event: