I've been investigating the new(ish) deferred object in jQuery and I stumbled across this website article here .
In the article is some code designed to cache scripts so they don't get requested more than once.
var cachedScriptPromises = {};
$.cachedGetScript = function( url, callback ) {
if ( !cachedScriptPromises[ url ] ) {
cachedScriptPromises[ url ] = $.Deferred(function( defer ) {
$.getScript( url ).then( defer.resolve, defer.reject );
}).promise();
}
return cachedScriptPromises[ url ].done( callback );
};
// You would then call it like thus.
$.cachedGetScript( url ).then( successCallback, errorCallback );
What this looked like to me was a way to ensure that your script will only get executed if your $.getScript()
was successful.
As far as my experiments have gone though the error callback never gets called even if I supply an incorrect url.
Have I missed something obvious or is the code sample wrong?
Note: I'd have asked this question on the site but the commenting system didn't work. :-S