简体   繁体   中英

Pre-load Jquery hover images

Right now I am building a map of the US, and when you hover over any given state, I am replacing the image with an image of a different color.

My problem is that the way I am currently doing things, the image is being replaced and a new image loaded on hover.

I have the HTML laid out as:

<img class="state" id="alaska" src="img/united-states_Alaska.png" alt="alaska">
<img class="state" id="hawaii" src="img/united-states_hawaii.png" alt="hawaii">

And the jQuery I am using is:

$('.interactive-map img').each(function(e){
    var src = $(this).attr('src');
    $(this).hover(function(){
      $(this).attr('src', src.replace('.png', '-hover.png'));
    }, function(){
      $(this).attr('src', src);
    });
});

I am curious if there is another way to either preload the images with JavaScript, or make it so that there isn't a new request for image every time I hover. I would like to not have to change the HTML or CSS much and optimize it in JavaScript.

Add your images to the DOM on page load but in hidden state, then they get cached

$(function() {
 var images = ['url/to/your/jpg1.jpg', 'ur/to/your/png2.png'];
 var d = document.createElement("div");
 d.style.display = 'none';
 document.body.appendChild(d);
 for (var i in images) 
 {
   var img = document.createElement("img");
   img.src = images[i];
   d.appendChild(img);
 }
});

Have two image tags and set the first image's display: block . Set the second image's display: none .

Then on hover you switch the them. It is as easy as that.

Use PreloadJS

Example:

var preload = new createjs.LoadQueue();
preload.addEventListener("fileload", handleFileComplete);
preload.loadFile('http://createjs.com/images/404/gBot-confused.jpg');
function handleFileComplete(event) {
    document.body.appendChild(event.result);
}

Full Docs: here

Another interesting post using JS and AJAX: Preloading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM