How to know when browser finish to process an image after loading it?

Here is one way.

CanvasContext2D drawImage method is synchronous. Before being able to use this method, the browser has to completely render the image.

So you can use it as a waiting method in your waitBIGimage method.

var BIGimage;
putBIGimage();

function putBIGimage() {
  BIGimage = document.createElement("IMG");
  BIGimage.height = 200;
  BIGimage.src = "https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg?r=" + Math.random();
  BIGimage.onload = waitBIGimage;
  BIGimage.onerror = console.error;
}

function waitBIGimage() {
  // only for demo
  // we've got to also log the time since even the console.log method will be blocked during processing
  var start = performance.now();
  console.log('waiting', start);

  // this is all needed
  var ctx = document.createElement('canvas').getContext('2d');
  ctx.drawImage(this, 0, 0);

  // demo only
  var end = performance.now();
  console.log("Complete.", end);
  console.log(`it took ${end - start}ms`)

  // do your stuff
  document.body.appendChild(BIGimage);
}

On my Firefox it takes about 1 second to process the image, while on my Chrome, it seems the image is already processed when the onload event fires.

But one big issue with method is that it is synchronous, and thus will block your scripts during all the time the Image is processed.

The HTMLImageElement interface has been recently expanded to include a decode() method, which should allow us to wait until the image is ready to be drawn, just like you wanted. However, from early tests I found this method quite deceptive, but it may be due to buggy early implementations:

var BIGimage;
putBIGimage();

function putBIGimage() {
  BIGimage = document.createElement("IMG");
  BIGimage.height = 200;
  BIGimage.src = "https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg?r=" + Math.random();
  BIGimage.onload = e => console.log('load event', performance.now());
  BIGimage.decode().then(waitBIGimage);
  BIGimage.onerror = console.error;
}

function waitBIGimage() {
  var start = performance.now();
  // only to see if it worked fine
  var ctx = document.createElement('canvas').getContext('2d');
  ctx.drawImage(BIGimage, 0, 0);

  // demo only
  var end = performance.now();
  console.log(`it took ${end - start}ms to draw`)

  // do your stuff
  document.body.appendChild(BIGimage);
}


There is no reliable way to know - your browser can continue to execute arbitrary javascript or perform built in functions (i.e., resizing of the browser window) which can directly or indirectly affect the image and cause it to be either redrawn, or appear to not finish drawing for a while.

You can hook in to particular events in the lifetime of an image, but, strictly speaking, "finish" only happens when the browser window is closed.

Tags:

Javascript