最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Execute JavaSCript code after image preload - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 4, 2010 at 14:50 aardbolaardbol 2,2954 gold badges33 silver badges49 bronze badges 2
  • I just found out that setInterval("if(i1.plete){...}", 500) is a good solution. Edit: But not as good as the suggested solutions below. – aardbol Commented Feb 4, 2010 at 15:07
  • 1 Yeah, you should avoid the string argument to setInterval/setTimeout; pass a function() { ... } in instead in preference. Also there's no plete attribute, only readyState (and that's non-standard, so onload is still best). Also you can probably lose the if (document.images) test, as the last browser not to support it was Netscape 2! :-) – bobince Commented Feb 4, 2010 at 15:50
Add a ment  | 

3 Answers 3

Reset to default 6

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";

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

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

Use onload in the image tag itself.

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

评论列表(0)

  1. 暂无评论