This blog site is not meant to be any information that is distributed to the general public. It is to serve as shared documentation between the DNSTC developers; however, if you find something useful and would like to use it, go right ahead.

Sunday, February 20, 2011

Preloading Images with Javascript

Problem:

There is a delay when you move your mouse over an image where the second image takes a while for it to be displayed on the screen.

Solution:

Preload the secondary image.

Description:

Preloading images is a technique often used by web developers when they are incorporating Rollover Effects or other image scripts which work more quickly when the images for them are loaded within the browser's cache as soon as possible.

For example, when developing a roll-over effect, if you move the mouse of the image for the first time, there is a delay in displaying the image… this can be easily fixed by preloading the image through the use of javascript.

Here is how it is done:

  1. Get the size of your image, i.e. width and height

  2. Add the following code to your <head> section of your page:




<SCRIPT language="JavaScript">
<!--
if (document.images)
{
pic1= new Image(100,25);
pic1.src="http://someplace.com/image1.gif";
}
//-->
</SCRIPT>


Explanation:

  • The condition statement checks to see if it is an older browser and if javascript is actually supported.

  • The pic1 = new Image statement creates a new option for the image. The two numbers within the parenthesis is the width and height of the image.

  • If you have multiple images, just continue with pic2, pic3, …

  • The line with the URL is the URL to the image.

No comments:

Post a Comment