More powerful jQuery getScript with cache control

wp-carousel-20

If you love getScript as a shortcut method in jQuery but you hate not being able to control whether the script calls from the browsers cache or not then you can override the build in function with a new one which is backwards compatable, so it won’t break any of your old code, and allows you to choose true or false to caching.

Read the original post by Jamie Thompson

 
(function($){
$.getScript = function(url, callback, cache){
	$.ajax({
			type: "GET",
			url: url,
			success: callback,
			dataType: "script",
			cache: cache
	});
};
})(jQuery)

4 comments.

  1. I think you may want to consider using a default for ‘cache’ as ‘cache =undefined’ might cause some inconsistencies (but I don’t have a proof of that).
    [code]
    $.ajax({
    type: "GET",
    url: url,
    success: callback,
    dataType: "script",
    cache: cache || true
    });
    [/code]

  2. From the original post and my use of this, I’m pretty confident it’s fine to use undefined and jQuery treats it as no.

  3. There is one more way of achieving this. You can do something like this .
    $.ajaxSetup({ cache: true });
    $.getScript(urlhere, function(){
    //call the function here….
    //Set cache to false.
    $.ajaxSetup({ cache: false });

    This will also enable the cache. Read the full article here..

    http://jquerybyexample.blogspot.com/2012/04/use-jquerygetscript-to-load-external-js.html

  4. Question to you:

    I have heard that even setting “cache” to “true” will not use the browser cache on a cross domain load.

    Any comments on this?

    Lorena