Javascript - execute after all images have loaded

前端 未结 9 1340
陌清茗
陌清茗 2020-12-01 05:53

Having read other people\'s questions I thought

window.onload=...

would answer my question. I have tried this but it executes the code the

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 06:11

    A little late to the game, but I've found the following method to be the most straightforward:

    function waitForImages () {
      let isLoading = true
    
      while (isLoading) {
        const loading = [].slice.call(document.images).filter(img => img.complete !== true)
        if (!loading.length > 0) {
          isLoading = true
          return
        }
      }
    }
    

    Note that this is blocking code (useful if you're trying to ensure images are loaded in something like phantomjs)

提交回复
热议问题