How to detect when an image has finished rendering in the browser (i.e. painted)?

后端 未结 5 1990
不思量自难忘°
不思量自难忘° 2020-12-08 04:19

On a web app I need to work with a lot of high-res images, which are dynamically added to the DOM tree. They are pre-loaded, then added to the page.

It\'s one thing

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 04:56

    I had the same problem. I have created the preloader page with progress bar. When the image is loaded, the white background preloader page disappears smoothly to opacity: 0, but the image is still not rendered.

    I have finally used the setInterval, when the image is loaded (but not rendered). In the interval I check the naturalWidth and naturalHeight properties (Support: IE9+). Initialy it equals 0 and when the image is rendered it shows its current width and height.

    const image = document.getElementById('image');
    
    image.src = "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-1.jpg";
    
    image.onload = function () {
      console.log('Loaded: ', Date.now());
      const interval = setInterval(() => {
        if (image.naturalWidth > 0 && image.naturalHeight > 0) {
          clearInterval(interval);
          rendered();
        }
      }, 20);
    }
    
    function rendered() {
      console.log('Rendered: ', Date.now());
    }
    img{
      width: 400px;
    }

提交回复
热议问题