图像预加载后执行 JavaSCript 代码

发布于 2024-08-20 10:20:51 字数 523 浏览 6 评论 0原文

我正在尝试创建某种回调代码,该代码在预加载图像后执行。

我的JS代码如下:

<script type='text/javascript'>
d=document;
window.onload=function()
{
   if (d.images)
   {
      d.getElementById('preload').style.display='block';
      i1=new Image;
      i1.src="http://link_to_image";
      d.getElementById('preload').style.display='none';
   }
}
</script>

所以在我的例子中,d.getElementById('preload').style.display='none';应该在图像完全加载到缓存后执行。

对如何实现这一目标有任何帮助吗?请仅使用没有库/插件要求的独立 JavaScript 解决方案。

I'm trying to create some kind of callback code which gets executed after an image has been preloaded.

My JS code is as follows:

<script type='text/javascript'>
d=document;
window.onload=function()
{
   if (d.images)
   {
      d.getElementById('preload').style.display='block';
      i1=new Image;
      i1.src="http://link_to_image";
      d.getElementById('preload').style.display='none';
   }
}
</script>

So in my example, d.getElementById('preload').style.display='none'; should be executed after the image has been fully loaded into the cache.

Any help on how to achieve this? Please only standalone JavaScript solutions without library/plugin requirements.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黑色毁心梦 2024-08-27 10:20:51

我不确定图像 onload 事件在所有浏览器中的可靠性如何,因此我会非常仔细地测试:

var i1 = new Image();

i1.onload = function() {
   d.getElementById('preload').style.display = "none";
};

i1.src = "http://link_to_image";

I'm not sure how reliable the image onload event is in all browsers, so I'd test this very carefully:

var i1 = new Image();

i1.onload = function() {
   d.getElementById('preload').style.display = "none";
};

i1.src = "http://link_to_image";
感情旳空白 2024-08-27 10:20:51

看看这篇文章,我认为它会有所帮助:链接文本

与 JavaScript 中的许多其他对象一样,Image() 对象也带有一些事件处理程序。其中最有用的无疑是 onLoad() 处理程序,它在图像完成加载时调用。

Have a look at this article, i think it will help: link text

like many other objects in JavaScript, the Image() object also comes with some event handlers. The most useful of these is undoubtedly the onLoad() handler, which is invoked when the image has completed loading.

您的好友蓝忘机已上羡 2024-08-27 10:20:51

在图像标签本身中使用 onload。

<img src="http://link_to_image" onload="alert('IMG LOADED')" />

Use onload in the image tag itself.

<img src="http://link_to_image" onload="alert('IMG LOADED')" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文