I have the following snippet:
var size;
function getImageSize(url)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url, true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
size = xhr.getResponseHeader('Content-Length');
alert(size);
}
}
};
xhr.send(null);
return size;
}
The purpose of the function is to return the file size (of a image).
The alert inside the function will always return the correct value, however the function itself will always return undefined. Why?
Odly, if I debug it with firebug, the function will always return correctly…
That’s because the function returns before the response is returned and the
sizeis set. It’s namely executed asynchronously. You’d like to pass a callback function instead and apply it withsizeas argument.