I have an <img> tag which is filled with dynamic src attribute. I would like to display the image size (in bytes) upon image load using javascript/jQuery.
I tried using the below. But, it returns zero in all 3 properties.
$('#img').on('load',
function() {
var imgUrl = $(this).attr("src");
var imgPerf = performance.getEntriesByName(imgUrl)[0];
console.log(Math.round(imgPerf.decodedBodySize)); // returns 0
console.log(Math.round(imgPerf.encodedBodySize)); // returns 0
console.log(Math.round(imgPerf.transferSize)); // returns 0
});
Is there any other possible ways to get the image size value?
FYI, the images are loaded from different domain.
if you have image url you can try this:
const fileImg = await fetch(URL_TO_IMG).then(r => r.blob());
This will get the resource through HTTP and then returns the full binary as a blob object, then you can access its properties including its size in bytes as:
fileImg.size