Jitendra Vyas
Jitendra Vyas

Reputation: 152945

What is the prefered method to preload images <img> and why?

What is the best method to preload images <img> and why? I want to show images on link's hover i can't use images in CSS background so i can't use CSS sprite. but i want to preload all images while page load . which are add as <img>.

Upvotes: 4

Views: 472

Answers (1)

Whit
Whit

Reputation: 1159

You can use the Image() object in JavaScript to preload the image, then swap it in when you're ready. Here's the HTML:

<img name="img01" src="regular_image.jpg">

Then in the JavaScript:

my_img = new Image(); 
my_img.src = "swap_image.jpg";

Which will put the image in your cache. When you swap it in, you can call:

document.img01.src='swap_image.jpg'

Upvotes: 6

Related Questions