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){

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.


Meet the Author

Kevin Leary, Custom WordPress Developer & BigQuery Consultant

I'm a custom WordPress developer and BigQuery consultant based in Boston, MA. I've been an independent freelance contractor for the last 16 years, helping business build, grow and maintain product websites, web applications and analytics systems. See real-world examples of my work, or contact me about your next project if you're in need of a good freelance developer.

Related Articles