How to create a JavaScript callback for knowing when an image is loaded?

matt picture matt · Nov 11, 2008 · Viewed 183.7k times · Source

I want to know when an image has finished loading. Is there a way to do it with a callback?

If not, is there a way to do it at all?

Answer

.complete + callback

This is a standards compliant method without extra dependencies, and waits no longer than necessary:

var img = document.querySelector('img')

function loaded() {
  alert('loaded')
}

if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
  img.addEventListener('error', function() {
      alert('error')
  })
}

Source: http://www.html5rocks.com/en/tutorials/es6/promises/