Reputation: 3279
I'm using Javascript to make a simple image viewer bar for my site (ASP.NET), I have 3 pictures displayed at each time and user can go to next or previous images using two buttons, also when users mouse overs on each picture, a larger version of the selected image is displayed on a separate DIV.
The only problem is that when users overs the images for the selected time, there is a delay before displaying the large image (as the big image is being loaded for the first time). how can I solve this problem? is there any way that I can initially load all large images (of course they should not be visible) what are my options?
Is there any way I can do it purely with javascript? I don't want to use jQuery
Upvotes: 1
Views: 491
Reputation: 108500
You can do a simple preload function:
function preload() {
while(arguments.length) {
new Image().src = [].shift.call(arguments);
}
}
Then use it like this, on domready or at the end of your document:
preload('img1.jpg', 'path/to/img2.jpg', 'img3.jpg');
This will make the browser load and cache the images. This might be better than placing them in a hidden DIV, since you will have full control of when the browser should start loading the images and potentially block download slots between the client and server.
Upvotes: 2
Reputation: 6192
Another way using pure javascript is this one:
var img = new Image();
img.src = "url to image";
That's it! That will make the request to the server. You can do this for the rest of the images. If you want to know when it is finally loaded you could add the load event. For example:
img.onload = function(){
alert("image ready");
}
Upvotes: 3
Reputation: 59355
Create an element neer the end of the body like this <div id="preload">
set this div to display:none
and place the images inside of it. Now when you use your gallery there shouldn't be a delay.
Upvotes: 4