views:

386

answers:

3

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.

+1  A: 

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.

MoJo2600
It's `onload`, not `onLoad`.
Tim Down
+1  A: 

Use onload in the image tag itself.

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

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