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
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Incredible Demos

  • By
    CSS Scoped Styles

    There are plenty of awesome new attributes we've gotten during the HTML5 revolution:  placeholder, download, hidden, and more.  Each of these attributes provides us a different level of control over an element on the page, but there's a new element attribute that allows...

  • By
    Use Custom Missing Image Graphics Using Dojo

    A few months back I posted an article about how you can use your own "missing image" graphics when an image fails to load using MooTools and jQuery. Here's how to do the same using Dojo. The HTML We'll delegate the image to display by class...

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!