JavaScript img onload - progressive jpg/jpeg

1.4k Views Asked by At

Is there a way to detect loading of each step of progressive JPEG (or at least the first one)?

At the moment onload() event is fired once the final (high quality) image is loaded.

Tested in Chrome 48.

1

There are 1 best solutions below

0
On

There isn't an event for it.

There's loadstart event that tells you when the browser makes a request, but it doesn't mean there's any data yet.

You can keep polling .naturalHeight property to observe if the browser knows image dimensions, which would mean that at least it has got some data.

A desperate option, and most likely too inefficient in most cases, is to download the image using XHR/fetch (which allows you to observe download progress), and then keep setting the partial data as Blob on the image element. I use this hack to demonstrate progressive image loading in slow-motion on ImageOptim API demo page.

Another option is to use a ServiceWorker, and pass through a chunked stream, and observe how much of the stream has been sent. In case of JPEG you can safely assume that 15% of the file is enough to render a usable preview of the file.