jQuery.getScript() does not cache

July 21st, 2008

It occurred to me today that when using jQuery’s handy little .getScript method that each script request is appended by a timestamp appended to the querystring. This is great. A lot of the time this is exactly what you want as it ensures that no browser will ever serve up it’s own cache in preference of the actual script from the actual server.

jQuery.getScript

But what if you just want to use .getScript to programatically include parts of your application logic only where necessary (aka Lazy Loading), or you simply want to defer the execution of a non-essential plugin or two until a couple of seconds after the DOM becomes available. You’d want those scripts cached as if you’d hard-coded them into script tags right? I guess.

Can’t Cache, Won’t Cache (with Ainsley Harriott)

There’s no way you can send cache control options into getScript. It simply doesn’t accept any. getScript is merely a wrapper around .get which itself does not provide options for controlling caching. I’m not sure whether or not this is an oversight on the part of the developers. Feel free to shoot me down in flames if i’m spectacularly missing some glaringly obvious point here.

It’s not a problem though. .get is itslef just a simple wrapper around .ajax which publicly exposes all of jQuery’s AJAXy goodness. As such there’s absolutely no reason why you can’t just redefine JQuery.getScript to accept an optional boolean argument for cache control. That’s the beauty of jQuery.

jQuery.getScript Redefined

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

This won’t break any existing code which references the function as omitting the cache argument defaults caching to false as per the original functionality. But if you want to allow caching you now have that option.

Posted in Web | Tagged with: , ,

Only One Response

  1. Richard

    Thank you for this.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.