01 August 2007 ~ 0 Comments

Howto: Preloading Images With Javascript

Javascript is the great unifier of Web 1.0 and Web 2.0. It’s still highly relevant, useful and almost necessary for new design trends as it was for old ones. One use of javascript is to preload images on a webpage to offer your site’s visitors a faster browsing experience. For those of you uninterested in reading my explanation, simply download the code here.

By inserting some simple javascript code into your <HEAD> tag, you will allow your site to load images in the background as the rest of the page continues to load. The vistor’s browser will then cache the images and display them wherever they’re used on subsequent pages immediately. This works great with all modern browsers, and the people who are on older browsers will still see your images normally, their browsers will simply ignore the script (meaning they won’t experience the benefits either).

This is one of my new favorite tricks in designing snappy, fast-loading webpages that heavily rely on images.

HOW TO DO IT

Create a blank text file using Notepad (Windows) or TextEdit (Mac). Copy then Paste the following code into it.

if (document.images)
{
img1 = new Image();
img2 = new Image();
img3 = new Image();
img1.src = “yourImage1.gif”;
img2.src = “yourImage2.gif”;
img3.src = “yourImage3.gif”
}

Replace the ‘yourImage#.gif’ with paths to your actual images (ex. img1.src = “photos/momsbirthdaycake.jpg”). Save the file as ‘preload.js’. Now, in the header of your document place the following code:

<script type=”text/javascript” src=”preload.js”></script>

Upload the script, the html document you’ve included it in, and all the images to your webserver. When you load your page now you should notice an immediate and significant speed increase!

Keep in mind that the pictures still need to initially be cached so the first time someone visits the page it will take some time to download all the pics (especially if you’ve used a lot) but all subsequent pages will take no time at all to load.

You can follow the techniques above to create your own .js file or just download and modify mine here!

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Leave a Reply

Bad Behavior has blocked 762 access attempts in the last 7 days.