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

前端 未结 10 1353
太阳男子
太阳男子 2020-11-22 04:56

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?

10条回答
  •  没有蜡笔的小新
    2020-11-22 05:34

    .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/

提交回复
热议问题