Using AJAX head-type requests to check size of remote scripts

Checking size for inline scripts is as easy as document.getElementsByTagName('script')[0].text.length (solution taken from here). But, when it comes to measuring size of remote resources things gets a little bit complicated. Mostly due to cross-site restrictions and reducing unnecessary server load. Head-type of AJAX call, not so famous among developers, may help in this case.

For remote scripts (and possible other resources) you can use AJAX request with ‘HEAD’ type:

jQuery.ajax
({
    cache: false,
    type: 'HEAD',
    url: 'myfile.js',
    success: function(d,r,xhr){alert('File size is ' + xhr.getResponseHeader('Content-Length') + ' bytes.')},
    error: function(xhr, desc, er){alert('ERROR: "' + xhr.responseText + '"')}
});

Using HEAD type means, in short, that server returns only headers, it would normally return along with file (resource), but don’t returns resource itself. Which significantly reduces server load, especially in the situation, where you want to check a lot of resources’ file sizes.

But be warned, that HEAD-type requests are not supported by all servers and browsers. In this case you may get file size that equals 0 or a response malformed in other way. If you run into such situation, you must consider using normal GET-type request, which will raise your server load considerably or drop the whole idea of checking remote files sizes at all.

Also note, that if you try to check remote file size, that is stored on other server (domain) than your script (website) works, such request will be blocked by browser, due to CORS. Using a jnsonp calls might help in this case, though I never used it, so I don’t know any details.

Source of above solutions and some more details: here and here.

Leave a Reply