Dynamically load a Javascript file with jQueryDynamically load a Javascript file with jQuery

Posted February 16th, 2010 in Javascript

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.

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus