External JavaScript on Demand With  $.getScript()

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