这是使用 Deferred 的 miken32 答案的略微改进版本:
function whenNoTrackingProtection() {
if (!whenNoTrackingProtection.promise) {
var dfd = new $.Deferred();
whenNoTrackingProtection.promise = dfd.promise();
var time = Date.now();
$('<img/>')
.attr('src', '//apps.facebook.com/favicon.ico')
.on('load', dfd.resolve)
.on('error', function() {
if ((Date.now() - time) < 50) {
dfd.reject();
} else {
// The request took to long, it seems this is a network error.
dfd.resolve();
}
});
}
return whenNoTrackingProtection.promise;
}
或者不使用 jQuery,使用 Promise:
function whenNoTrackingProtection() {
if (!whenNoTrackingProtection.promise) {
whenNoTrackingProtection.promise = new Promise(function(resolve, reject) {
var time = Date.now();
var img = new Image();
img.onload = resolve;
img.onerror = function() {
if ((Date.now() - time) < 50) {
reject();
} else {
// The request took to long, it seems this is a network error.
resolve();
}
};
img.src = '//apps.facebook.com/favicon.ico';
});
}
return whenNoTrackingProtection.promise;
}