Run JavaSCript code after image preload

I am trying to create some kind of callback code that runs after the 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, it d.getElementById('preload').style.display='none';should be executed after the image is fully loaded into the cache.

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

+3
source share
3 answers

I'm not sure how reliable the image event is onloadin all browsers, so I would have tested it very carefully:

var i1 = new Image();

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

i1.src = "http://link_to_image";
+6
source

, , :

JavaScript, Image() . , , onLoad(), , .

+1

Use onload in the image tag itself.

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

Source: https://habr.com/ru/post/1731390/


All Articles