Skip to content Skip to sidebar Skip to footer

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 imp

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Preloading Image, (source In Javascript)"