Loading Scripts with jQuery

By  on  

JavaScript loaders are incredibly powerful and useful utilities.  I've even covered a few of them on this blog, like curljs and LABjs, and have used RequireJS and the Dojo loader on personal projects.  They're super powerful but can be overkill in some cases.  If you're using jQuery, there's a built in method for loading a single script which may come in handy if you'd like to lazy load a plugin or any other type of script.  Here's how to use it!

The jQuery JavaScript

jQuery is fitted with a getScript method to load one script; handling the result can be done in a few ways.  A basic usage of jQuery.getScript would look like:

jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {

	/* 
		do something now that the script is loaded and code has been executed
	*/	

});

The getScript method returns a jqxhr so you can also use it as a follows:

jQuery.getScript("/path/to/myscript.js")
	.done(function() {
		/* yay, all good, do something */
	})
	.fail(function() {
		/* boo, fall back to something else */
});

The obvious use case for jQuery.getScript is lazy loading of a plugin and using it once loaded:

jQuery.getScript("jquery.cookie.js")
	.done(function() {
		jQuery.cookie("cookie_name", "value", { expires: 7 });
});

If you need to do more advanced stuff like loading multiple scripts and different types of file types (text files, images, css files, etc), I'd recommend you switched to a JavaScript loader.  In the case of wanting to lazy load a plugin and not simply load it with each page, getScript is perfect!

Update: Caching

It's important to note that when using jQuery.getScript, a timestamp is added to the script URL so the script ends up not being cached. Unfortunately you need to override all caching to cache the script and still use jQuery.getScript:

jQuery.ajaxSetup({
  cache: true
});

If you don't want to override all caching with your AJAX requests, it's best the use the jQuery.ajax method with a dataType of script:

jQuery.ajax({
      url: "jquery.cookie.js",
      dataType: "script",
      cache: true
}).done(function() {
		jQuery.cookie("cookie_name", "value", { expires: 7 });
});

Keep caching in mind when loading your scripts!

Recent Features

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

Incredible Demos

Discussion

  1. Nice! Makes me want to dig through all the available jQuery methods again.

  2. Just remember getScript appends a random value on the GET request to prevent caching. If you actually want to allow caching of the script you have to roll your own $.ajax method.

  3. Excellent post!

    However, be aware that the default behavior of getScript is to load the content using AJAX and insert it in an inline script-tag on the website. Because the browser has no way to tell where the content actually came from, the dev tool (built-in, Firebug etc.) cannot give ANY helpful information at all (most likely it will refer to a non-existing line in the jQuery file) if there is any error in the loaded JavaScript file.
    To avoid this behavior, one can instead use $.ajax and set crossDomain: true in the parameter object. This forces jQuery to instead create a script-tag with the src-attribute set to the url of the script and debugging will again work as expected.

  4. Nice post as always! Will use this in my future projects for sure!

  5. Wrote an extension to the getScript method that allows for multiple scripts to be loaded synchronously and asynchronously. Hope it helps!

    https://github.com/hudsonfoo/jquery-getscripts

  6. Squeak

    Is it possible to use getScript to load JS file when a select box is clicked?

    I found a plugin with ~50 translations (eternicode datepicker). Since my app has a “choose language” select box, it would be nice if I could load the file(s) when requested by user. If it is possible, an example would be helpful for the noobs like me. :)

  7. James

    What about loading 3rd party scripts and setting a timeout?
    Lets say I do not want a 3rd party script to hold up the loading of my site, is it possible to have a timeout with this so that – lets say, after 5 seconds, if it hasn’t loaded I can abort the getScript call?

    • James, would this work?

      $.ajax({
          url: "jquery.cookie.js",
          dataType: "script",
          error: function(){
              // will fire when timeout is reached
          },
          success: function(){
              //do something
          },
          timeout: 5000 // sets timeout to 5 seconds
      });
      
  8. Pieter Pol

    > do something now that the script is loaded and code has been executed

    This is not true. The script is loaded at that point but not necessarily executed. Check the API docs.

    • Mike S.

      Pieter Pol is right. The API docs and personal experience say so.

  9. Prakash

    Hi,

    Nice post, I have a question here. Is it possible to add and get multiple JS files using getScript(), Thanks in advance.

  10. Note that you can also set cache:true for the specific getScript request if you use the options object signature:

    $.getScript({
        url: "foo.js",
        cache: true
    })
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!