External JavaScript on Demand With $.getScript()

Load an external JavaScript file on demand with $.getScript() to keep pages lean.

  • Too many external scripts in the of a document can pile up as a site grows and hurt page performance.
  • jQuery's $.getScript() lets you load JavaScript on demand, acting like the JavaScript equivalent of CSS's @import.
  • A simple pattern: check whether a target element exists (e.g. $('a.email').length > 0), and only then load the plugin file and run a callback to initialize it.
  • If the element isn't on the page, the script is never loaded, keeping pages lean and avoiding unnecessary requests.
  • This approach is especially elegant for managing multiple jQuery plugins, and the snippet should be wrapped in a document ready event.
  • Be aware: $.getScript() appends a cache-busting parameter (e.g. ?_=ts2477874287) to the URL, so scripts are fetched fresh on every load unless caching is configured otherwise.

I find myself using JavaScript more and more often in my work. As work on a particular site grows, I find that too many external scripts begin to pile up in the <head> section of my document, eventually effecting performance. Thanks to jQuery’s $.getScript method, I’ve found an elegant solution to this problem.

Think of jQuery.getScript() as the JavaScript equivalent to CSS’s @import. Take it one step further and use it to load JavaScript only when it is needed and you have a lean combination.

JavaScript / jQuery

if ($('a.email').length > 0){
    $.getScript('js/jquery.mailto.js',function(){
        $('a.email').mailto();
    });
}

How it works

This small snippet of code that will check for the existence of an object, in this case that object is any anchor link with a class of email. If this object is found on a page, a corresponding .js file (js/jquery.mailto.js) will be loaded and a callback function initiated ($(‘a.email’).mailto();). If the object is not found, the script will not be loaded. This assumes that the snippet is enclosed in a document ready event.

I find this approach to be the most elegant when handling multiple jQuery plugins. One could compare it to the @import CSS command that is frequently used to load in multiple style sheets from one master CSS file.

Disable Caching

When loading external scripts dynamically with jQuery’s getScript, a cache busting parameter is added to the request URL. So, instead of writing something like <script src=’/js/foo.js’>, it writes something like <script src=’/js/foo.js?_=ts2477874287′>, causing the script to be loaded fresh each time.

Resources