Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading images in HTML, is there a more modern way?

I have an image loaded by JS on a mouse event. It's a fairly big image so I want to make sure it gets pre-loaded. I reemmber some old techniques from years ago and found this example:

<SCRIPT LANGUAGE = JAVASCRIPT>
if (document.images) 
{
   img1 = new Image();
   img2 = new Image();
   img1.src = "imageName1.gif";
   img2.src = "imageName2.gif"
}
</SCRIPT>

I wondered if this is still good/relevant, or maybe browsers automatically detect unused images and preload them anyway? Note my page has to support IE6, so I might still need older techniques anyway, but I'm still interested if more modern browsers have a better way?

like image 855
Mr. Boy Avatar asked May 26 '10 09:05

Mr. Boy


2 Answers

Nope, this is it. Why change something that works?

But a more proper usage is like this

(function() {
   var img1 = new Image();
   var img2 = new Image();
   img1.src = "imageName1.gif";
   img2.src = "imageName2.gif"
})();

or just

new Image().src = "imageName1.gif";
new Image().src = "imageName2.gif"

Both of these avoids cluttering the global scope with variables.

And language="JavaScript" is deprecated. Use type="text/javascript".

like image 87
Sean Kinsey Avatar answered Oct 22 '22 22:10

Sean Kinsey


Depends what kind of images you are talking about, icons/buttons etc. could be done using a technique called CSS Sprites.

http://www.alistapart.com/articles/sprites

like image 34
CharlesLeaf Avatar answered Oct 22 '22 23:10

CharlesLeaf