您將只能夠完成你想要什麼,如果對圖像中的服務器響應包括適當的跨源資源共享(CORS)報頭和Content-Length頭。
此外,您需要考慮在替換循環中執行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();
})
};
這可以很容易用PHP來實現看-http://stackoverflow.com/questions/4635936/super-fast-getimagesize-in-php – ramr
jQuery的任何答案或JavaScript將不勝感激我猜! – ramr
可能的重複:http://stackoverflow.com/questions/1484303/get-size-of-file-requested-via-ajax – lightbricko