jquery defer and promises with getScript
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 m开发者_Go百科e 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
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.
But...you may delegate the remote url check to a (e.g.) php file.
checkremotefile: function( remotefile, options ) {
options = $.extend( options || {}, {
dataType: 'html',
cache: false,
url: 'ajax/checkfile.php?url=' + escape(remotefile),
error: function (jqXHR,textStatus,errorThrown) {
$(this).coresystem('errorlog',jqXHR,textStatus,errorThrown);
},
success: function (data,textStatus,jqXHR) {
if (data!='200') {
// ....call errorhandler
}
}
});
return jQuery.ajax( options );
},
checkfile.php:
<?php
if (!isset($_REQUEST['url'])) die( 'param url missing!');
if (!preg_match('/.*\.js$/',$_REQUEST['url'])) die( 'filetype not allowed');
$ch = curl_init($_REQUEST['url']);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $code 404 not found, $code = 200 found.
curl_close($ch);
echo($code);
Not 100% reliable, but better then nothing...
精彩评论