Quick Tip: Get more efficient with jQuery’s getScript!
So recently, I’ve been working on a project that uses a multitude of different jQuery plugins, but they’re not all needed on the same page, and it seemed not only unnecessary, but silly to be loading over 10 plugins when maybe only 2 are used on the current page. I sent myself on a mission to work out how to stop being a resource hog, and only load what was needed on the page I was on.
My initial thoughts
I figured, hey, jQuery is logical to code, and so I came up with a logical way to fix it in my head. It went something like this:
I need a way to work out whether a script was required on the page, so I decided I’d apply a unique class to the body for each plugin I required on the page. Then, using multiple if statements in jQuery, I’d append the script tag with the relevant url to the right plugin, and fire off the plugin function while I was at it depending on what classes were found on the body.
As it turned out, only half of this logic worked. The logic behind checking what classes were applied to the body was spot on, it worked a treat, but appending the scripts to the head didn’t work. After a bit of research, I found that
jQuery detects that you’re trying to create a SCRIPT element and will automatically run the contents of the element within the global context.
I thought “fair enough, jQuery is being clever” but my scripts were still not being run. I researched further, and finally stumbled across the holy grail to my problem, getScript.
What is getScript?
GetScript is a jQuery ajax function that loads a script from your specified url and has an extremely useful callback function for when the script is loaded. This is exactly what I needed.
For those of you who maybe understand a bit more ajax, jQuery’s documentation states that this getScript function is simply a shorthand version of this:-
$.ajax({
url: url
dataType: 'script',
success: success
});
The shorthand getScript version simplifies this however, so set to work with it.
Putting it to use!
We are going to go back to our original logic and replace it with our new jQuery function. Here’s how it looks when we turn that pseudo code (logic) into working code.
$(document).ready(function() {
if $('body').hasClass('script') {
$.getScript('script/url.js');
fireoffthefunction();
}
});
Improvement!
This isn’t the end though. We are only halfway to making the most intuitive fix that we can. There are two enhancements that I made, the first being the most important. If you’ve read the documentation for jQuery’s getScript function, then you’ll have noticed its callback argument. Instead of firing the functions from the script we are loading below it, why not make use of its callback function and fire it once the script loads? Who knows, what if our script fails to load; our current version would then stop all jQuery on the site working! Not what we want.
$(document).ready(function() {
if $('body').hasClass('script') {
$.getScript('script/url.js'), function() {
fireoffthefunction();
});
}
});
Less important for most people, but useful for me was my last improvement. I figured, why should I do the work when jQuery can do it for me? Most of my jQuery plugins hook to a certain element such as select, or a div#slider, so why manually search through the html files and assign classes to the body when we can make jQuery search through for me?
Heres a small snippet of code from one of my current projects which brings together everything we’ve discussed and learnt.
$(document).ready(function() {
if ($('select').length > 0){
$.getScript('js/jquery.stylish-select.min.js', function() {
$('select').sSelect();
});
}
});
Using jQuery’s ‘.length’ function we search through the document for the element ‘select’. If it is present (a.k.a more than 0) then we run the stylish select script, and if it loads we’ll apply the script to the element.
Further Discussion
I do not claim to be a jQuery ninja, or anything of the sort. If you can further improve this simple but useful concept or have another idea on solving this common issue with ease, then I’d love to hear them; I’m always up for an insightful discussion.
Did you enjoy this article and found it useful?
Get even more from us:








jQuery By Example
Posted 49 days ago 18Well, Good post!!!
But there is an issue with getScript() that it always reloads a fresh copy from the server. In short, it doesn’t cache. Which is sometimes a good thing but not always.
I have posted about 2 different ways to enable caching, if someone wants. Read my post.
http://jquerybyexample.blogspot.com/2012/04/use-jquerygetscript-to-load-external-js.html
Thanks
jerry
Posted 253 days ago 17How do I know if it was previously loading. Js with $. GetScript?
Web Design Leicester
Posted 314 days ago 16The problem with this solution is that you’re still having to query the DOM for select elements, or whatever else you choose. This means that every page request has to search the entire DOM.
I’m currently considering a different solution, taken from this link: http://www.artzstudio.com/2009/04/jquery-performance-rules/#eliminate-query-waste
Joshua
Posted 587 days ago 15I have been using a similar style of script for a larger client site that I have been working on. The site it’s self is a portfolio for a musician/actor, and the site has about 12 pages included. Each page has it’s own style and niche and I use Jquery through-out the site and different scripts for each page.
if ($(‘#content’).length) {
$.getScript(‘lib/jquery.someElement.js’, function() {
functionHere();
});
}
The only problem that I feel that I run into is, when a getScript loads that interacts with an element that will be altered or turned into a slideshow or something to that effect, both Chrome and Firefox make an odd flashing before displaying the element that is mentioned in the function after the getScript. When I move the script out of the getScript and load it with the html, then call the function — it looks wonderful.
I hope that makes sense, I was just wondering if there was something similar to return false that would not allow that to happen. Thanks in advance.
vimal
Posted 677 days ago 14I am looking on some thing where I can combine and load multiple javascript files at ONE shot. This requires some server side programming as well since I am C# developer I can look at using handlers (ashx) which I can call and in response it combine multiple scripts.
Does any one know how would I flush back this combined script file which I can successfully handle from ajax call ?
Thanks in advance
Vimal
Dario Calonaci
Posted 696 days ago 13Really great and useful, thank you!
Alexey
Posted 713 days ago 12there is apparently a typo in the first snippet of the Improvement! section. I mean the closing parenthesis before the comma, where comma should follow the url string literal and the parenthesis goes after the callback function body.
Darlinton
Posted 714 days ago 9Can you load css with it?
Cause, many jquery plugins need a css, so load both togheter look good..
Matt Corner
Posted 714 days ago 10No, this is just for scripts, but with css, you could append the css link to the head as jquery wont stop you doing that like it does for scripts.
I however, stumbled across a lightweight jquery plugin today that does exactly what you are looking for, only loading the right css and jquery for the necessary element on the page.
http://www.unwrongest.com/projects/lazy/
At the time of writing this article, I was unaware of this script, but it certainly looks like a great alternative.
It would appear you hook the stylesheets and plugins to the plugins function name, and if that function is called, the stylesheet and plugin in question will be called so that the function can run.
Michael Pehl
Posted 716 days ago 7That is a really useful thread. Will use it in my latest project.
Thanks for sharing this :)
Louis
Posted 716 days ago 6Maybe I’m not understanding your problem completely, but wouldn’t it be easier to load the plugins for their respective pages via PHP? For example, in PHP you find out what the current page is, then check to see what it is, and echo out the script tag if the current page matches where the plugin should be. If using WordPress, then you could check the page ID and do the same thing.
Is this not easier than using jQuery itself to check for it?
.-= Louis´s last blog ..Should A Website Be Designed According to the Standards of its Niche? =-.
Matt Corner
Posted 715 days ago 8You do understand me correctly. I decided to do this via jquery because the project I researched this for was for a template to be sold to the masses. Therefore php isnt really an option.
Elliot
Posted 716 days ago 5Nicely done.
Thanks for the code share. This one is bound to come in handy
.-= Elliot´s last blog ..Remove dashboard menu items for a specific user in WordPress =-.
8888
Posted 716 days ago 3Maybe you will give sidjs a try, it can load both css and javascript file on your demand, the project url is: http://www.diveintojavascript.com/projects/sidjs-load-javascript-and-stylesheets-on-demand
Saad Bassi
Posted 716 days ago 4Brilliant Share. Thanks.:)
David
Posted 716 days ago 2Thanks Matt – very useful indeed – the logic you’ve applied makes perfrect sense to me, and has also given me a couple of ideas for a few things I’ve been working on.
Matt Corner
Posted 714 days ago 11No problem David, glad you enjoyed it, and it’s helped you with some ideas =)
Matic
Posted 716 days ago 1Thanks!
This is really usefull ;)