Exception
Exception

Reputation: 8379

Is it possible to check how much size of an image is loaded using JavaScript

It's a perfectly dumb question. But I just wanted to clear my doubt. When a image is loading we can check loading state using onload or oncomplete events. But I just wanted to know how much portion of the images is loaded using JavaScript. Is it really possible?

My question is, Can we get image size from URL? and Can we get how much portion of image is loaded in some interval?

Upvotes: 3

Views: 236

Answers (2)

maerics
maerics

Reputation: 156434

If you load the images via an XMLHttpRequest object you can bind to the progress event and check the function argument "event" properties "loaded" and "total". As always, support between various browsers might be a surprise.

From the linked MDN article:

var req = new XMLHttpRequest();
req.addEventListener("progress", onProgress, false);
req.open();

function onProgress(ev) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    // ...
  } else {
    // Unable to compute progress information since the total size is unknown.
  }
}

[Update] Per commenter @Bergi's question if you want to add the image to the DOM once it has fully downloaded you could add a new image element with:

  1. The "src" attribute equal to the URL you fetched via XHR (and hope that the browser cache will prevent redundant download).

  2. Or set the "src" attribute to a data URI of the Base64 encoded image content and not worry about the browser cache.

var img = new Image(); // or document.createElement('img');
img.src = ... // URL from the above XHR request, or
img.src = 'data:image/png;base64,' + base64(xhrContent);
document.body.appendChild(img);

Upvotes: 5

con
con

Reputation: 2410

You can achieve this with the html5 file api for modern browsers which allows to read the filename, filesize, mimetype, and a reference to the file handle - check this example

Upvotes: 1

Related Questions