在浏览器中识别完整的图像绘制

Identify image paint complete in browser

本文关键字:图像 绘制 浏览器 识别      更新时间:2023-09-26

在浏览器中加载高分辨率图像的情况下,即使在网络从服务器获取图像之后。浏览器需要一些时间来显示它们,因为它逐渐绘制。

如何通过浏览器识别此油漆作业已完成?

http://postimg.org/image/txm6e94jz/- 检查此图像。

主页中的图像呈现了一半,我可以使用什么事件来查看该图像完全渲染?

使用 window.requestAnimationFrame 来捕捉渲染图像的时刻:

function imageRenderedCallback() {
  alert("Image Rendered Callback executed");
};
function imageRenderingStarted() {
  requestAnimationFrame(imageRenderedCallback);
};
// Attach handler for load event. 
document.getElementById('my-image').addEventListener('load', function(){
  requestAnimationFrame(imageRenderingStarted);
});
#my-image {
  width: 1680px;
  height: 1260px
}
<body>
<img id="my-image" src="http://www.hdwallpapers.in/download/mount_fuji_japan_highest_mountain-">
</body>

请参阅请求动画帧。丝般流畅的JavaScript动画的秘诀!文章解释了什么是以及如何使用requestAnimationFrame

您可以为"加载"事件添加事件侦听器。

document.getElementById('imgId').onload = function (){ /* image loaded */ }

这与Andriy的解决方案非常相似,但我发现它更可靠一些......但不太干净。不过为我完成了工作。

// after preloading the image
requestAnimationFrame(function() {
   /*
   ... code to add the image to the dom
   */
   requestAnimationFrame(function() {
      document.body.offsetWidth // force repaint
      requestAnimationFrame(function() {
         // image is painted
      })
   })
})