开发者

Preloading Image, (source in javascript)

Ok I previously asked how to do a javascript image hover effect, however the effect doesn't allow the images to be previously preloaded. I was wondering if anyone could help me improve/make new script that will preload the images requested. Here is the code:

$('#nav li a img').each(function() {
   var originalSrc = this.src,
       hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_hover.$1'); 

   $(this).hover(function() {
      this.src 开发者_如何学编程= hoverSrc;
   }, function() {
      this.src = originalSrc;
   });
});


You could use a generic one...

(function() {
    var imgs = ['a.jpg', 'b.jpg'],
        imgsLength = imgs.legnth,
        index = 0,
        loadNextImage = function() {

            var image = new Image();

            image.onload = function() {
                if (index == imgsLength) {
                   return;   
                }
                index++;
                loadNextImage();
            }

            image.src = imgs[index];
        }
}();

jsFiddle.

...or for your specific example...

$('#nav li a img').each(function() {
   var originalSrc = this.src,
       hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_hover.$1'); 
       image = new Image();

   image.src = hoverSrc;

   $(this).hover(function() {
      this.src = hoverSrc;
   }, function() {
      this.src = originalSrc;
   });
});

This will load them all when the JavaScript is ran. There is no handler on their load event, so you may wish to add one and not display the hover effect until they have in fact been downloaded.


Create div and put your rollover/hover images in it then hide the div

<div style="display:none">
    <img src="" />
    <img src="" />
    etc..
</div

This will load the images without having to use javascript at all, but there is a known problem with Opera using this method.. But I use it all the time works fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜