Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Graphics Display

Selective preloading of linked images by BillyRayPreachersSon
Posted: 1 Jan 04 (Edited 12 May 06)

If you have a list of images on your page, linked to with an HREF, and you'd like to preload some (or all) of those images before the user clicks on the links, consider the following code.

Most preload code requires you to specify a list of image filenames to preload. This solution avoids that necessity, and thus gives you the flexibility to include this script on multiple pages really easily.

Place this JavaScript at the top of your page:


<script type="text/javascript">
function preLoadImages()
    var imageCache = new Array();
    var linkArray = document.getElementsByTagName("a");
    for (var loop=0; loop<linkArray.length; loop++)
        if (linkArray[loop].className == "preloadThis")
            imageCache[imageCache.length] = new Image();
            imageCache[imageCache.length-1].src = linkArray[loop].href;

Then run the preload function once the document has loaded:


<body onload="preLoadImages();">

And then for every image you want preloaded, simply give the appropriate A tag a class of "preloadThis":


<!-- this image gets preloaded -->
<a href="images/wibble.gif" class="preloadThis">Click here to view image 1</a>

<!-- this one does not -->
<a href="images/bibble.gif">Click here to view image 2</a>

Do your A tags already have a class? No problem. Simply assign them multiple classes:


<a href="images/wibble.gif" class="pageLeft preloadThis">Click here to view image 1</a>
<a href="images/bibble.gif" class="tempClass inRow preloadThis">Click here to view image 2</a>

Thanks to petey ( http://www.tek-tips.com/userinfo.cfm?member=petey ) for his thread on assigning multiple classes to elements ( thread215-732497 ), and to BabyJeffy ( http://www.tek-tips.com/userinfo.cfm?member=BabyJeffy ) for the idea of looping through the elements dynamically (he's just lazy ;o).

Hope this is of value,


Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page @ Code Couch

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close