Pre-loading and JavaScript Image () objects

Source: Internet
Author: User
Tags array functions http request access javascript array
javascript| objects Many high-res images can really make your Web site neater. But they also slow down access to the site-the image is a file, the file uses bandwidth, and the bandwidth is directly related to the wait time. It's time to learn how to improve the access speed of your Web site by using a technique called image preload (preloading).

image Pre-loading

For browsers to load images, they are not loaded by the browser until an HTTP request is sent to the image, and the HTTP request to the image is either using the tag or by means of a method call. If you use JavaScript scripts to swap images when you mouseover events, or to automatically change images after a period of time, you may have to wait a few seconds to a few minutes to get an image from the server. This is especially true if you are using a slow Internet connection, or if you want to get a very large image, or some other condition, so that the delay causes you to not achieve the desired results.

Some browsers take steps to mitigate this problem, such as trying to store images in the local cache, so that subsequent calls to the image are immediately satisfied, but there are still some delays when the image is first invoked. Pre-loading is a way to download the image to the cache before you need it. With this measure, when the image is really needed, it can be immediately taken out of the cache so that it can be displayed immediately.

Image () object

The easiest way to preload an image is to instantiate a new image () object in JavaScript, and then pass the URL of the image you want to load as a parameter. Suppose we have an image called Http://www.webjx.com/htmldata/2006-06-26/heavyimagefile.jpg, and we want to display this image when the user's mouse is placed over an image that has already been displayed. To preload this image for faster response times, we simply create an image () object heavyimage and then load it in the OnLoad () event handler.
<script language = "JavaScript" >
function Preloader ()
{
Heavyimage = new Image ();
HEAVYIMAGE.SRC = "Http://www.webjx.com/htmldata/2006-06-26/heavyimagefile.jpg";
}
</script>

<body >
<a href= "#" >
</a>
</body>

Note that the image tag itself cannot handle the onMouseOver () and onmouseout () events, which is why the tag in the previous example is contained in a <a> tag,<a> tag supports both event types.

load multiple images using an array

In practical applications, we may need to preload multiple images, and more than one, for example, in a menu bar that contains multiple images, or when we try to create a smoothing effect, we need to preload multiple images. This is not difficult, as long as you use a JavaScript array, as in the following example:
<script language= "JavaScript" >
function Preloader ()
{
Counter
var i = 0;
Create Object
Imageobj = new Image ();
Set Image list
Images = new Array ();
images[0]= "Image1.jpg"
images[1]= "Image2.jpg"
images[2]= "Image3.jpg"
images[3]= "Image4.jpg"
Start preloading
for (i=0; i<=3; i++)
{
Imageobj.src=images[i];
}
}
</script>

In the above example, we define a variable i and an Image () object imageobj. A new array images[is then defined, and each array element stores the image to be preloaded. Finally, you create a for () loop that processes the entire array and assigns each element to the Image () object, which loads it into the cache.

OnLoad () event handler

Like many other JavaScript objects, the Image () object has some event handlers. One of the most useful is definitely the onLoad () processor, which is invoked after the image is fully loaded. This event handler can be associated with a custom function to perform certain tasks after the image is fully loaded. The following example illustrates this, in this case, first displaying a "Please wait" screen when the image is loaded, and then transferring the browser to a new URL when the load completes.
<script language= "JavaScript" >
Create an Image Object
Objimage = new Image ();
Set what happens once the image has loaded objimage.onload=imagesloaded ();
Preload the image file
objimage.src= ' http://www.webjx.com/htmldata/2006-06-26/images/image1n.gif ';
function invoked on image load
function imagesloaded ()
{
document.location.href= ' index2.html ';
}
</script>

<body>
Please wait, loading images ...
</body>

Of course, you can also create an array of images and then loop through them, preload each image, and then track the number of loaded images at each stage. Once all the images have been loaded, depending on the event handler's program logic, it can take the browser to the next page (or perform other tasks).

Pre-loading and multi-status menus

Now, how do you use all the theories you've learned in a real-world application? The following code is a menu bar that I recently wrote occasionally, which consists of buttons (image links) with three states: normal, Hover, and click. Because the button has a variety of States, it is necessary to use the image preload to ensure that the state of the menu can react quickly. The code in listing a illustrates the implementation method.

The HTML code in listing a sets a menu consisting of four buttons, each with three states: normal, Hover, and click. Requirements are as follows:

# when the mouse moves to a button on a normal state, it becomes a hover state. After the mouse leaves, the button reverts to its normal state.

# When the mouse clicks a button, the button changes to the click state. It retains this state until the other buttons are clicked.

# If a button is clicked, the state of the other buttons cannot be clicked. The other buttons can only be in hover or in a normal state.

# at the same time only one button is clicked.

# there can be only one button in the hover state at the same time.

The first task is to set the array to hold the image for each state of the menu. The corresponding to these array elements is also created in the body of the HTML document and named sequentially. Note that the index of an array value starts at 0, although the corresponding element is named starting from 1-so you need to calculate the adjustment in the section that follows the script.

The function preloadimage () is responsible for storing all the images in the cache so that the mouse motions are minimal in response time. The for () loop is used to iterate through the image created in the first step and preload an image in each iteration.

function Resetall () provides a quick way to reset all images to their normal state. This is necessary because when an item is clicked, all other items in the menu must be placed in a normal state before the clicked item changes to the click state.

Functions Setnormal (), Sethover (), and Setclick () are used to change the state of a particular image (which passes an image number to each function with one argument) to normal, hover, and click. Because the clicked image must retain its state before other objects are clicked (see the second rule), they temporarily do not respond to the mouse movement, so that the code for the Setnormal () and Sethover () functions will only change the state of the button that is not currently in the click state.

This is just one way to do a lot of preload images, which can help you improve the response speed of JavaScript effects. You are free to use the previous method in your site, and if necessary, you can modify the code to suit your needs. Good luck!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.