Preload Images using Javascript
This example shows using ajax request to get data and preload the images.
Note images could be loaded in div which have a style "display:none" however certain browsers like opera do not load hidden images for the sake of performance.
HTML
<div class="instructions">The photographs loaded here were used just for the sake of an example. They were taken from the website
<ul><li><a href="http://500px.com/photo/93940">Photo 01</a></li>
<li><a href="http://500px.com/photo/129276">Photo 02</a></li>
</ul>
</div>
<div id="show" class="show">show image</div>
<div id="ajax-json"></div>
CSS
.show{width:100px;height:100px;border:1px solid;background-color:#CDCDCD;}
.instructions{border:1px solid yellow;background-color:yellow;text-align:center;}
JavaScript
$.ajax({
cache: false,
type: 'POST',
url: '/echo/json/',
data: {
json: '[{"title":"Heart of Baikal","url":"https://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg"},{"title":"Sunset. Canada","url":"https://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg"}]'
},
success: function(data) {
var preloadedImages = [];
$.each(data, function(index, item) {
var tempImage = new Image();
tempImage.src = item.url;
preloadedImages.push(tempImage);
});
$(".show").hover(function() {
//mouseover
$.each(preloadedImages, function(index, item) {
$("<img>").attr({
src: item.src
}).appendTo("#ajax-json");
});
}, function() {
//mouse out
$("#ajax-json").empty();
});
},
error: function(error) {
alert("there was an error");
},
dataType: "json"
});