Quick Tip: Get more efficient with jQuery’s getScript!

Posted in Web Design • Posted on 18 Comments

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.

source

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.

20 Written ArticlesWebsite

Matt is an 18 year old web designer from Scotland, UK. He loves creating beautiful websites across different platforms. High on his things to learn fully are Jquery and php. He is extremely excited by css3 and html5 and can't wait to see them rolled out fully. To learn more about Matt, follow him @QwibbleDesigns, or check out his portfolio.

18 Comments Best Comments First
  • David

    Sunday, June 6th, 2010 13:04

    1

    Thanks 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.

    0
    • Matt Corner

      Tuesday, June 8th, 2010 16:55

      11

      No problem David, glad you enjoyed it, and it’s helped you with some ideas =)

      0
  • Michael Pehl

    Sunday, June 6th, 2010 20:32

    7

    That is a really useful thread. Will use it in my latest project.
    Thanks for sharing this :)

    0
  • Matic

    Sunday, June 6th, 2010 12:14

    5

    Thanks!

    This is really usefull ;)

    0
  • 8888

    Sunday, June 6th, 2010 13:13

    2

    Maybe 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

    0
    • Saad Bassi

      Sunday, June 6th, 2010 13:43

      6

      Brilliant Share. Thanks.:)

      0
  • Elliot

    Sunday, June 6th, 2010 14:33

    3

    Nicely done.

    Thanks for the code share. This one is bound to come in handy

    0
  • Louis

    Sunday, June 6th, 2010 14:43

    4

    Maybe 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?

    0
    • Matt Corner

      Monday, June 7th, 2010 21:01

      8

      You 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.

      0
  • Darlinton

    Tuesday, June 8th, 2010 15:32

    9

    Can you load css with it?
    Cause, many jquery plugins need a css, so load both togheter look good..

    0
    • Matt Corner

      Tuesday, June 8th, 2010 16:55

      10

      No, 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.

      0
  • Gareth Mueller

    Wednesday, July 13th, 2011 11:30

    16

    The 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.

    0
  • jerry

    Monday, September 12th, 2011 18:02

    17

    How do I know if it was previously loading. Js with $. GetScript?

    0
  • jQuery By Example

    Wednesday, April 4th, 2012 02:13

    18

    Well, 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

    0
  • Joshua

    Wednesday, October 13th, 2010 19:06

    15

    I 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.

    0
  • vimal

    Thursday, July 15th, 2010 17:59

    14

    I 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

    0
  • Alexey

    Wednesday, June 9th, 2010 22:33

    12

    there 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.

    0
  • Dario Calonaci

    Saturday, June 26th, 2010 20:41

    13

    Really great and useful, thank you!

    0
  • jQuery By Example

    Wednesday, April 4th, 2012 02:13

    18

    Well, 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

    0
  • jerry

    Monday, September 12th, 2011 18:02

    17

    How do I know if it was previously loading. Js with $. GetScript?

    0
  • Gareth Mueller

    Wednesday, July 13th, 2011 11:30

    16

    The 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.

    0
  • Joshua

    Wednesday, October 13th, 2010 19:06

    15

    I 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.

    0
  • vimal

    Thursday, July 15th, 2010 17:59

    14

    I 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

    0
  • Dario Calonaci

    Saturday, June 26th, 2010 20:41

    13

    Really great and useful, thank you!

    0
  • Alexey

    Wednesday, June 9th, 2010 22:33

    12

    there 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.

    0
  • Darlinton

    Tuesday, June 8th, 2010 15:32

    9

    Can you load css with it?
    Cause, many jquery plugins need a css, so load both togheter look good..

    0
    • Matt Corner

      Tuesday, June 8th, 2010 16:55

      10

      No, 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.

      0
  • Michael Pehl

    Sunday, June 6th, 2010 20:32

    7

    That is a really useful thread. Will use it in my latest project.
    Thanks for sharing this :)

    0
  • Matic

    Sunday, June 6th, 2010 12:14

    5

    Thanks!

    This is really usefull ;)

    0
  • Louis

    Sunday, June 6th, 2010 14:43

    4

    Maybe 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?

    0
    • Matt Corner

      Monday, June 7th, 2010 21:01

      8

      You 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.

      0
  • Elliot

    Sunday, June 6th, 2010 14:33

    3

    Nicely done.

    Thanks for the code share. This one is bound to come in handy

    0
  • 8888

    Sunday, June 6th, 2010 13:13

    2

    Maybe 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

    0
    • Saad Bassi

      Sunday, June 6th, 2010 13:43

      6

      Brilliant Share. Thanks.:)

      0
  • David

    Sunday, June 6th, 2010 13:04

    1

    Thanks 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.

    0
    • Matt Corner

      Tuesday, June 8th, 2010 16:55

      11

      No problem David, glad you enjoyed it, and it’s helped you with some ideas =)

      0

Comments are closed.

54.87.156.29 - unknown - unknown - US