如果图像的服务器响应包含适当的跨域资源共享 (CORS) 标头和内容长度标头,您将只能完成您想要的操作。
此外,您需要考虑在替换循环中完成 ajax 请求所需的时间。
下面是一个 jQuery (1.9.1) 示例,它演示了最终解决方案的样子。要使其正常工作,您需要更新指向服务器的链接,该服务器返回正确的 CORS 标头或禁用浏览器上的安全性。该示例也在jsfiddle上。
var largeImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/49000/49684/rikuzentakata_ast_2011073_lrg.jpg";
var smallImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/81000/81258/kamchatka_amo_2013143_tn.jpg";
var urls = [largeImage, smallImage];
var maxSize = 5000000;
$.each(urls, function(index, value) {
conditionalMarkupUpdater(value, maxSize);
});
var onShouldBeViewable = function () {
alert('This is a small image...Display it.');
};
var onShouldNotBeViewable = function () {
alert('This is a large image...Only provide the url.');
};
var onError = function() {
alert('There was an error...likely because of CORS issues see http://stackoverflow.com/questions/3102819/chrome-disable-same-origin-policy and http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/"');
};
function checkSize(url) {
var sizeChecker = new jQuery.Deferred();
var onSuccess = function (data, textStatus, jqXHR) {
var length = jqXHR.getResponseHeader('Content-Length');
if (!length) {
sizeChecker.reject("No size given");
} else {
sizeChecker.resolve(parseInt(length));
}
};
var onFailure = function (jqXHR, textStatus, errorThrown) {
sizeChecker.reject("Request failed");
};
$.when($.ajax({
type: "HEAD",
url: url
})).then(onSuccess, onFailure);
return sizeChecker.promise();
};
function conditionalMarkupUpdater(url, maxSize) {
$.when(checkSize(url)).then(
function (size) {
if (size <= maxSize) {
onShouldBeViewable();
} else {
onShouldNotBeViewable();
}
},
function (status) {
onError();
})
};