Themergency fooplugins.com

An Alternative to jQuery’s getScript Function

| 19 Comments

I use the getScript function in jQuery alot to quickly insert javascript into my page asynchronously with a single line of code :

$.getScript('../an-alternative-to-jquerys-getscript-function/myscript.js');

The beauty with this is that you can use getScript to lazy load javascript files when, and if you need them. There is also a callback, so that you can run some code after the script has been loaded:

$.getScript('../an-alternative-to-jquerys-getscript-function/myscript.js', function() {
alert('I am loaded!');
});

But I read a post recently talking about getScript and how it does not support caching. So basically, if you use getScript to load the same javascript file on every page of your site, that file will not be cached by the browser. This is caused by jQuery adding a random querystring onto the end of the file path. In some cases this might be what you want. But not in most of the cases I was dealing with. In fact, I doubt most developers even know this about the getScript function. So I created a little jQuery function that you can use in place of getScript.

It’s Called loadScript

It gives you the same functionality of getScript, but you can now specify if the file is cached or not. Check out the gist. Here is the code:

jQuery.loadScript = function (url, arg1, arg2) {
  var cache = false, callback = null;
  //arg1 and arg2 can be interchangable
  if ($.isFunction(arg1)){
    callback = arg1;
    cache = arg2 || cache;
  } else {
    cache = arg1 || cache;
    callback = arg2 || callback;
  }
  var load = true;
  //check all existing script tags in the page for the url
  jQuery('script[type="text/javascript"]')
    .each(function () { 
      return load = (url != $(this).attr('src')); 
    });
  if (load){
    //didn't find it in the page, so load it
    jQuery.ajax({
      type: 'GET',
      url: url,
      success: callback,
      dataType: 'script',
      cache: cache
    });
  } else {
    //already loaded so just call the callback
    if (jQuery.isFunction(callback)) {
      callback.call(this);
    };
  };
};

Another awesome thing it does is check the existing page for the script you are trying to load. If it finds the script then it immediately calls the callback function.

Example Usage

Here is how you would use it with caching enabled:

$.loadScript('../an-alternative-to-jquerys-getscript-function/myscript.js', true, function() {
alert('I am loaded!');
});

The ../an-alternative-to-jquerys-getscript-function/myscript.js file will now only get downloaded once. If the script was already included in the page header, then the script would never have been downloaded and the alert would have been shown immediately.

Also note that the function allows for the callback and caching parameters to be mixed around. The following 2 lines of code do exactly the same thing:

$.loadScript('../an-alternative-to-jquerys-getscript-function/myscript.js', true, callback);
$.loadScript('../an-alternative-to-jquerys-getscript-function/myscript.js', callback, true);

I hope you find this function useful.

10 comments
  Livefyre
  • Get Livefyre
  • FAQ
hudsonfoo
hudsonfoo

Sync or async extension method to $.getScript: https://github.com/hudsonfoo/jquery-getscripts

BrentAureli
BrentAureli

getScript now offers caching by adding

$.ajaxSetup({ cache: true});
andmcg1
andmcg1

Looks like a really awesome function. I am including in my project.

 

Thanks for posting it!

 

Thanks,

Andrew M

RajeshBute
RajeshBute

Hi, Your post is very nice but i want to use the same getScript() without using jQuery i.e. in plain javascript for cross-domain, any one have an idea for it?  Thanks in advance!

RichardHarris2
RichardHarris2

This looks like a neat alternative. Does this get around the issue that getscript doesn't work in google chrome? as the code fetches the script from the existing page if it is present,  rather than the specified external file, seems like it might do the trick. Will try and test it

Arauna

This only detects if you have loaded the file via a script tag or if it has been loaded before.  However, if you have loaded it on a previous page and it is in the users cache it still goes and fetches the file instead of using a uses cached version.

Kenneth J Hughes
Kenneth J Hughes

See "Caching Responses" on the jQuery.getScript page,

 

http://api.jquery.com/jQuery.getScript/

 

for how to disable cache prevention.

BrentAureli
BrentAureli

Seems this was already brought up, shame on me for not reading further


shaheen pathan
shaheen pathan

 @RajeshBute Hello Sir,

There is an alternative way to use getScript jquery. Instead of getScript ,  we can use plain ajax in javascript to call the file or to include file so that no conflict issues will arise.

RichardHarris2
RichardHarris2

I have tried using the code, and it loads the script just fine in the same way as getscript. However, if I put the callback function into the script command, then it produces an error. If I use true, for the cache command, it works fine though.

this is what I put in the code:

 

$.loadScript('/assets/js/../an-alternative-to-jquerys-getscript-function/myscript.js', callback);

 

I don't know if this has occurred before, but I can't see anything I have done differently to what you outline above.

 

without the callback function working, it won't get the script from the head of the page so just calls the script from the external file in the same way that getscript does, and is therefore also blocked by chrome.

 

Hopefully you can help resolve this callback problem and see if it works as a workaround for the chrome issue.

 

Thanks

themergency
themergency moderator

 @Kenneth J Hughes thanks for the comment Kenneth. I realise that you can set the caching using ajaxSetup, but it seems to be a long winded way of doing things. Eg:

 

$.ajaxSetup({ cache: false });

 

$.getScript('../an-alternative-to-jquerys-getscript-function/myscript.js');

 

$.ajaxSetup({ cache: true });

 

It says the alternative is to use $.ajax, but I prefer my loadScript function over both. But I biased :) Another thing the loadScript function does is ingore loading the script if it is already in the page, which is helpful too.