3

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?

Exception
  • 8,111
  • 22
  • 85
  • 136
  • 2
    not reliably. not all servers include a size header, not all servers will include a RELIABLE size header. there may be very low-level browser-specific internal status things you can check, but in standard JS, there's no "progress" thing you can check that works everywhere. – Marc B Dec 17 '12 at 18:35
  • 2
    This article might be of interest: http://blogs.adobe.com/webplatform/2012/01/13/html5-image-progress-events/ – maerics Dec 17 '12 at 18:35
  • 1
    you could load it via XHR if it's the same domain and listen to the progress event. – zzzzBov Dec 17 '12 at 18:40

2 Answers2

5

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);
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 1
    And after loading it via XHR, how to show the image? Just insert a `new Image` with same url, and hope the cached version is used? Or should one `base64`-url-encode the binary content and output that? – Bergi Dec 17 '12 at 18:50
  • @Bergi: both of those ideas sound like valid options. – maerics Dec 17 '12 at 20:23
1

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

con
  • 2,358
  • 25
  • 33