WWW FAQs: How do I preload images?

2006-08-08: Pages with lots of images can be slow to load. That's frustrating for the user, and it can often be avoided... especially if the user is proceeding through a series of pages in a particular order.

Preloading: Why Load Then What You Can Load Now?

Once the images on the current page have loaded, the user's web browser stops talking to your web server. Then the user clicks on your "Next Page" link and the loading process starts all over again. The user twiddles her thumbs, waiting for pictures to appear.

There's a better way! We can load the images for the second page while the user is still admiring the first one.

Preloading With CSS

In the old days, JavaScript was the most popular way to preload images. JavaScript works... but only if the user has JavaScript enabled. And some users do disable JavaScript, for personal or corporate security reasons.

CSS, on the other hand, is standard equipment in all modern browsers. And with CSS, we can attach the images for the second page to the first page, without actually displaying them... which means that the images will appear right away when the user moves to the second page. And no JavaScript code is required!

OK, enough talk - let's do it! When we want to place an image in a web page, we do this:

<img src="myimage.jpg">

That loads the image and displays it at that point in the page.

But we can also load an image and not display it at all. We do that with the CSS display style, which controls how an element is displayed. When we set display to none, the image doesn't actually appear... but it does load. That's because the browser knows we might change the display property later. In fact, we'll just use the image in the normal way on our second page... and there it is, already loaded in the cache. Nice, no?

So, here's how to preload the image:

<img src="myimage.jpg" style="display: none">

This image doesn't actually appear - it just gets loaded at this point.

Make sure you place this img element at the end of your page!

Any undisplayed img elements should go at the end of your page, just before the </body> tag. If not, they will load first... and slow down the loading of images that are on the first page. Always load what you need for the current page first.

So far, so good! But how do we use our preloaded image on the second page? There's nothing to it! Just use an img element exactly as you normally would:

<img src="myimage.jpg">

The image will appear right away because it was preloaded into the browser's cache by the hidden image element on the first page.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!