Pre-loaded with JavaScript image () object

Source: Internet
Author: User
Tags define array functions http request
Objects | Loading a lot of high-resolution images can really dress up a web site. But they may also reduce the speed of the Web site-images are files, files consume bandwidth, and bandwidth is directly related to latency. It's time for you to learn how to use a little technique called image preload to speed up your site.




Pre-loading
of
images







browsers typically work by: The image is loaded only when an HTTP request to load an image is sent, whether it is loaded passively through the <img> tag, or by means of a method call. So, if you have a JavaScript, you need to switch the image while hovering, or automatically replace the image after the timeout, you may be able to get the image from the server at any time, from a few seconds to a few minutes. This is especially true when you are connected to the Internet at a slower rate, or when the image retrieved is very large, and this data lag usually destroys the effect you expect.





some browsers will try to pass on the problem, such as keeping the image in a local buffer so that subsequent calls to it can be made quickly, but there will still be a delay when the image needs to be called for the first time. Preload is a technique that downloads the image to a buffer before it needs to be uploaded. In this way, when the image is really needed, it can be taken out of the buffer and displayed immediately.





Image () object

The simplest way to
a preloaded image is to instantiate a new image () object with JavaScript and pass it to the URL of the images you want to preload. Suppose we have an image called Http://www.163design.net/j/e/heavyimagefile.jpg, and we want the system to display this image when the user puts the mouse over an image that has already been displayed. To preload this image for faster response times, we simply create a new image () object, name it heavyimage, and use the onload () event handler to load it onto the page at the same time.





<html><head><script language = "JavaScript" >function Preloader () {heavyimage = new Image (); HEAVYIMAGE.SRC = "Http://www.163design.net/j/e/heavyimagefile.jpg";} </script></head><body onload= "Javascript:preloader ()" ><a href= "#" onMouseOver= "javascript: document.img01.src= ' http://www.163design.net/j/e/heavyimagefile.jpg ' "><img name=" IMG01 "src=http:// www.163design.net/j/e/"Justanotherfile.jpg" ></a></body></html>


Note that the image tag itself does not handle the onmouseover () and onmouseout () events, which is why the <img> tag in the above example is placed in a <a> tag, which does add support for these event types.


loads multiple images with an array








in practice, you may need to preload more than one image, for example, in a menu bar that contains multiple images tumbling (rollover), or if you are trying to create a smooth dynamic effect. It's not difficult; all you have to do is use an array of JavaScript, 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, you first define the variable I and the image () object called Imageobj. Then define a new array called images[, in which each array element holds the source of the image that needs to be preloaded. Finally, create a for () loop that loops through the array and assigns each of them to the image () object so that it can be preloaded into the buffer.


OnLoad () event handler


just like many other objects in JavaScript, the Image () object also has multiple event handlers. One of the most useful of these is the onload () handler, which is invoked when the image is loaded. This handler can be used with custom functions to perform specific tasks after the image is loaded. The following example illustrates this problem by displaying a "wait (please)" Prompt when the image is loaded, and then sending a new URL to the browser after the image is loaded.





<html><head><script language= "JavaScript" >//Create an image objectobjimage = new Image (); Set what happens once the image has loaded objimage.onload=imagesloaded (); Preload the image fileobjimage.src= ' http://www.163design.net/j/e/images/image1n.gif ';/function invoked on image Loadfunction imagesloaded () {document.location.href= ' index2.html ';} </script></head><body>please Wait, loading images...</body></html>








of course, you can also create an array of images, loop it, preload each image, and keep track of the number of loaded images at each stage. Once all the images have been loaded, the event handler is able to take the browser to the next page (or other tasks) according to the settings.





Pre-loading and multi-status menu


now, how about putting the theory you've just learned into real practice? Here's a piece of code I happen to write--a menu bar consisting of multiple buttons (image links)--each of which can be in one of three states: normal, hover (hover), and click (click). Because all buttons have multiple states, it is necessary to use image preload to ensure that menus respond quickly to the state in which they are switched. This is what the code in List A says.




The HTML code in
List A creates a menu bar of four buttons, each with three states: normal, Hover, and click. Its requirements are as follows:





But when the mouse moves to a button that is in the normal state, the button changes to a hover state. When the mouse moves away, the button returns to its normal state.


When the mouse clicks the button, the button becomes the click state. It will remain in this state until another button is clicked.


If a button is clicked, none of the other buttons will be in the click state. Other buttons can only be hovering or in a normal state.


only one button can be clicked at a time.


only one button can hover at a time.


The first task is to create an array of images that hold each state of the menu. The <img> elements corresponding to these array elements are also created in the body of the HTML document and are named sequentially. Note that the index of the array value starts at 0, and the corresponding <img> element is named from 1-this requires some sort of calculation adjustment in the section following the script.




The
preloadimages () function is responsible for loading all the images into the buffer, so that the response time to the mouse movement is minimized. A for () loop is iterated in the image created in the first step and preloaded with each image.




The
Resetall () function is a convenient way to restore all images to their normal state. This is necessary because when the menu item is clicked, all other items in the menu must be restored to the normal state before the clicked item can be switched to the click state.




The
setnormal (), Sethover (), and Setclick () functions are responsible for changing the source of a particular image (the number of the image to be passed as a function's argument) to normal, hover, or click State respectively. Since the clicked image must remain in the click state until another image is clicked (see the second requirement), they do not respond to the mouse movement for the time being, so if the button is not in the click State, then Setnormal () and Sethover () The code that the function includes can only be used to change the state of the button.





the preload mentioned above is just one of several ways to improve the response time of your JavaScript effects. Use the techniques listed above on your site and change them where you need them, as required. Good luck!











Related Article

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.