You can only do what you want if the server response for the images includes the appropriate Cross Origin (CORS) header and content length header.
In addition, you will need to take into account the time required to complete ajax requests in your replacement loop.
The following is a jQuery example (1.9.1) that demonstrates what the final solution might look like. For it to work, you will need to update the links to the server, which will return the correct CORS headers or disable protection in your browser. An example is also on 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(); }) };
source share