DEV Community

Cover image for External JavaScript on Demand With $.getScript()
Kevinleary.net
Kevinleary.net

Posted on Originally published at kevinleary.net

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 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();
    });
}
Enter fullscreen mode Exit fullscreen mode

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 </strong>, it writes something like <strong><script src=’/js/foo.js?\_=ts2477874287′></strong>, causing the script to be loaded fresh each time.</p> <h3> <a name="resources" href="#resources" class="anchor"> </a> Resources </h3> <ul> <li> <a href="https://www.amazon.com/dp/1935182323/ref=asc_df_19351823231395195?smid=ATVPDKIKX0DER&tag=hyprod-20&linkCode=asn&creative=395093&creativeASIN=1935182323">jQuery in Action: Second Edition</a></li> <li> <a href="https://www.amazon.com/Learning-jQuery-1-3-Jonathan-Chaffer/dp/1847196705">Learning jQuery 1.3</a></li> <li> <a href="https://api.jquery.com/jQuery.getScript/">jQuery.getScript Documentation</a></li> </ul>

Top comments (0)