It appears that the HEAD requests I'm sending via jQuery's $.ajax({...}); method, are returning the content of the given resource (at least in Firefox... IE appears to function normally), rather than just headers. I'm trying to capture only the Content-Length header property, for use in an image preloader, though it seems that by merely querying for the Content-Length, it's downloaded the content itself.
The order of operation here, is:
- Find all elements in a given page with CSS
background-image, and populate an array (imageTemp) with the URLs. - For each image URL, perform an Ajax
HEADrequest, to obtain theContent-Lengthand add that tobytesTotalas well as populate the array (imageData) with both the URL and that image'sContent-Length.- Simultaneously, start a
setIntervalevent handler to periodically check whether or not all of the AjaxHEADrequests have completed.
- Simultaneously, start a
- When the
HEADrequests have completed, begin loading the images intoImage()objects fromimageData, adding the associated imageContent-Lengthvalue to thebytesLoadedvalue.\ - When
bytesLoaded == bytesTotalimages are done loading, and the preloader has completed.
Here is my script as of currently:
(function($){
var callbacks = {
initiate: function(){},
progress: function(percent){},
complete: function(){},
};
var imageTemp = Array();
var imageData = Array();
var imageCurrent = null;
var intervalId = 0;
var bytesLoaded = 0;
var bytesTotal = 0;
$.preloader = function(arguments){
for(var arg in arguments){
callbacks[arg] = arguments[arg];
}
callbacks.initiate();
$('*')
.each(function(index){
if($(this).css('background-image') != 'none'){
imageTemp.push($(this).css('background-image').slice(5, -2));
}
});
intervalId = window.setInterval(function(e){
if(imageData.length == imageTemp.length){
window.clearInterval(intervalId);
for(var i = 0; i < imageData.length; i++){
(function(imageIndex){
currentImage = new Image();
currentImage.src = imageData[imageIndex][0];
currentImage.onload = function(e){
bytesLoaded += parseInt(imageData[imageIndex][1]);
callbacks.progress(bytesLoaded/bytesTotal);
if(bytesLoaded >= bytesTotal){
callbacks.complete();
}
};
})(i);
}
}
}, 1);
for(var i = 0; i < imageTemp.length; i++){
(function(i){
$.ajax({
type: "HEAD",
async: true,
url: imageTemp[i],
success: function(message, text, response){
var bytes = parseInt(response.getResponseHeader('Content-Length'));
bytesTotal += bytes;
imageData.push([imageTemp[i], bytes]);
},
});
})(i);
}
};
})(jQuery);
This is directly associated with my question over at Ajax HEAD request via Javascript/jQuery, but it certainly not a duplicate, as the issue has extended from the previously solved question.