开发者

How to build a javascript preloader for images

I have a page of thumbnails which change their opacity with a hover with a image swap script built in jquery. However When I run it on a live website it is slow and you have to wait for the second开发者_如何学Python image to load so the hover swap doesn't happen right away. How would I preload all of the thumb images while the page loads? the site is live here

Here is the html

<div class="span-16 last" id="thumbs">
        <div class="span-4">
            <a href="waterfront.php"><img src="images/thumbs/thumb1.gif" id="thumb1"></a>
        </div>

    </div><!--THUMBS ENDS-->

Here is the jquery

$("#thumb1").hover(
        function(){
            $("#thumb1").attr("src","images/thumbs/thumb1A.gif");
            },

        function(){
            $("#thumb1").attr("src","images/thumbs/thumb1.gif");

        });


To build on alex' answer

var images = ['a.jpg','b.jpg','c.jpg'];
var preload = [];
for(i in images)
{
    preload[i] = new Image();
    preload[i].src = images[i];
}

This preloads all images in the images array. The script assumes you know beforehand which images you want to preload of course.


Here is an article to help you.

It is creating img elements in the DOM.

I have often done it by making a new Image() and then setting its src property to the image location. You get an event triggered when it loads, which is onload.

So a brief example would be

var preload = new Image();

preload.onload = function() { // I believe you need to define this before you set the src for IE
    alert('loaded');
}

preload.src = 'path/to/image.png';


See my comment on the solution I voted up. For more information on adding a true pre loader with a callback see here: http://farinspace.com/jquery-image-preload-plugin/

Since its important that you preload the images for rollovers, you might not want to display the menu until after these images have been loaded. You can hide the menu on a init and show it on the onload callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜