Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selective preloading of linked images

Graphics Display

Selective preloading of linked images

by  BillyRayPreachersSon  Posted    (Edited  )
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:
Code:
<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;
		}
	}
}
//-->
</script>

Then run the preload function once the document has loaded:

Code:
<body onload="preLoadImages();">

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

Code:
<!-- 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:

Code:
<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,

Dan


[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top