, LLC.

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 ($('').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 ($(‘’).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, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 16 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.