Reputation: 5953
I have a bunch of images on a website that have two versions: a large one and a small one.
The small version automatically display when you visit the website and when you click them, I use jquery to open up a hidden div and insert the large version.
Since the large images are not visible to the browser when the page loads (no img
has them as a src
), they will not be loaded until the user clicks one of the small images to enlarge it, and therefore they will not slow down page loading time.
To make the UI as responsive as possible however, I would like to start buffering the large images from the moment the page has loaded (so that they are there when the user clicks one of them).
how can I start loading images in the background?
Upvotes: 1
Views: 1008
Reputation: 108530
You can start loading images in the background when you set a src
to an Image
object, f.ex:
(new Image).src = src;
Here is a function for you:
function preloadImages() {
for(var i=0; i<arguments.length; i++) {
(new Image).src = arguments[i];
}
}
preloadImages('one.jpg', 'two.jpg');
I suggest you start preloading the images when the window has loaded (inside the window.onload
callback) to prevent it from sabotaging the UI:
window.onload = function() {
preloadImages('one.jpg', 'two.jpg');
};
Upvotes: 3