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
promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists. If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point.
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
A promise represents a value that is not yet known. This can better be understood as a proxy for a value not necessarily known when the promise is created. A deferred represents work that is not yet finished. A deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
I'm fairly sure that that script cannot work on cross-domain requests.
$.getScript
works in different ways for local and cross-domain requests. For local requests, it loads the content via AJAX then runs it. Since this is a normal AJAX operation, errors occur in the normal way. That code works fine, as far as I can test it.
For cross-domain requests, however, it works by inserting script
tags into the document. error
handlers are never fired for the script
elements that are inserted, so your error
callbacks will never fire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With