Recently I was building a site which called an external js script which then updated a div on the page. However, the scripts were loading (and running) before the page had completely loaded (despite being at bottom of page), so the target div wasn't being updated. The only solution was to load the scripts in the $(document).ready() call on the page (which only occurs after the entire page has loaded) - and as it turns out, there's a jQuery function for exactly this occasion: $.getScript().

$.getScript() is a shorthand method for calling the file through Ajax (much like the $.get() or $.post() functions), and is the equivalent of passing the datatype of 'script' to one of the ajax functions.

Example

// make sure page has loaded
$().ready(function() {
    // load external Javascript file
    $.getScript('/js/example.js');
});

The $.getScript() function also has a callback option, which gives the option to call another script once the external Javascript has loaded, or check that the Javascript has run (note: the external script will already have run by this point).

Callback Example

// make sure page has loaded
$().ready(function() {
    // load external Javascript file
    $.getScript('/js/example.js'), function() {
        // callback function
        console.log('external script loaded!');
    });
});