Home > Web Front-end > JS Tutorial > body text

js uses image objects to preload images to improve access speed_javascript skills

WBOY
Release: 2016-05-16 17:39:03
Original
1167 people have browsed it

Using a large number of high-resolution images can really make a website look radiant. But it will also cause the site access speed to slow down - pictures are files, and files take up bandwidth, and bandwidth is directly related to the access waiting time. Now, let's learn a little trick called image preloading to improve image access speed.

Some browsers try to work around this problem by saving these images in their local cache. This allows the images to be called sequentially - but there is still a delay when the images are used for the first time. Preloading is a technique that downloads images to cache before they are needed. In this way, when the image is really needed to be displayed, it can be quickly restored from the cache and displayed immediately.

Image() object
The simplest way to preload images is to use JavaScript to create a new Image() object, and then pass the URL of the image you want to preload to this object. Suppose we have an image file named heavyimagefile.jpg, and we want this file to be displayed when the user moves the mouse pointer over an existing image. In order to preload this file faster, we simply create a new Image() object named heavyImage, and then load it synchronously to the page through the onLoad() event handler.

Copy code The code is as follows:









< ;/html>

Note that the image tag itself does not handle onMouseOver() and onMouseOut() events, which is why the tag in the above example is included The reason in the tag. The tag includes support for these event types.

Load multiple images through arrays
In actual situations, you are likely to need to preload more than one image; for example, for applications that include multiple images menu bar, or want to achieve smooth animation effects. It is not difficult to implement this, you just need to use JavaScript arrays, as shown in the following example:
Copy code The code is as follows:



In the above example, define The variable i and the Image() object named imageObj are included. Then a new array images[] is defined, and each array element will store the address source of the image that needs to be preloaded. Finally, use a for() loop to iterate through the entire array and assign an Image() object to each element to preload the images into the cache.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template