JavaScript – Get size in bytes from HTML img src

Well, this is 2017 and you can now use Resource Timing API to extract an image’s transferSize, encodedBodySize, decodedBodySize within javascript:

Below is the code to access size information for all the imgs on a page (see the caveat to all below):

var imgElems = document.getElementsByTagName('img');
for ( var i=0, len = imgElems.length; i < len; i++ ) 
{
    var url = imgElems[i].src || imgElems[i].href;
    if (url && url.length > 0)
    {
        var iTime = performance.getEntriesByName(url)[0];
        console.log(iTime.transferSize); //or encodedBodySize, decodedBodySize
    }
}
  • Make sure you run the above code after document onload (to be sure images are loaded)
  • Due to CORS, timing information for images coming from a different domain may not be available (unless the different domain’s server has set Timing-Allow-Origin HTTP response header)
  • Be sure resource timing api is available for the browser(s) you are targetting : http://caniuse.com/#feat=resource-timing
  • Make sure you get a grasp of the difference between transferSize, encodedBodySize, decodedBodySize to be sure you use the right size attribute.

Leave a Comment