Skip to content

Instantly share code, notes, and snippets.

@elisechant
Last active August 29, 2015 13:56
Show Gist options
  • Save elisechant/9162884 to your computer and use it in GitHub Desktop.
Save elisechant/9162884 to your computer and use it in GitHub Desktop.
$.cachedGetScript Using jQuery Deferreds.

@Julian, In respect to a $.cachedGetScript utility:

I'm trying to understand the differences between using a variable stored cache (your example - cachedGetScript.js) and jQuery's Ajax Cache (cachedGetScript2.js)? Is there a difference at all?

E.

// http://msdn.microsoft.com/en-us/magazine/gg723713.aspx
var store.cachedScriptPromises = {};
$.cachedGetScript = function(url, callback) {
if (!store.cachedScriptPromises[url]) {
store.cachedScriptPromises[url] = $.Deferred(function(d) {
$.getScript(url).then(d.resolve, d.reject);
}).promise();
}
return store.cachedScriptPromises[url].done(callback);
};
$.cachedGetScript2 = function(url, callback){
callback = $.isFunction(callback) ? callback : {};
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return $.ajax({
type: "GET",
url: url,
dataType: "script",
cache: true
}).done(callback);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment