Home / Dynamically load a Javascript file with jQuery

Dynamically load a Javascript file with jQuery

jQuery’s $.getScript() function is a shorthand wrapper to $.ajax() which easily allows remote Javascript to be loaded into the current page.

Using $.getScript()

It’s so simple. For example, to load a Javascript file at /javascript/myscript.js do this:

$.getScript('/javascript/myscript.js');

If you need to execute some additional code after the Javascript file is loaded then do this:

$.getScript('/javascript/myscript.js', function() {
    // do something here
});

Note that this makes a GET request and if POST is required then you need to use the $.ajax() function directly, as shown below, instead of the $.getScript() shorthand.

Using $.ajax() instead

The same thing can be done using the $.ajax function which allows for some more control over the parameters, such as making it a POST request instead or ensuring the file is never cached.

To simply load the script and not do anything else, as is done in the first example above:

$.ajax({
    url: '/javascript/myscript.js',
    dataType: 'script'
});

To call a callback function on success:

function scriptLoaded() {
    // do something
}

$.ajax({
    url: '/javascript/myscript.js',
    success: scriptLoaded()
});

Other values can be added to the { } array passed to $.ajax() as required.