2

I have a web page which displays different images when different links on the same page are clicked. The images are very high quality and they take a lot of time to load, and I want the images to be downloaded and saved in the cache and then loaded on onclick event of the links.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

4

Just load them all as hidden images.

CSS:

.hidden {
    display:none;
}

HTML:

<img src="/hugeImage.jpg" class="hidden" />
<img src="/hugeImage2.jpg" class="hidden" />
<img src="/hugeImage3.jpg" class="hidden" />
<img src="/hugeImage4.jpg" class="hidden" />

You can easily simulate this with JavaScript, adding each of the images to the DOM after the DOMContentLoaded event - the same logic applies.

var img = document.createElement('img');
img.setAttribute('src', '/hugeImage.jpg');
img.setAttribute('class','hidden');
document.body.appendChild(img);
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Simple and awesome. The other answer was also great and helpful. But accepting this one as it was earlier. Thanks to both of answers –  Dec 14 '11 at 08:50
2

See this previous answer of mine for how you can pre-cache images: Is there a way to load images to user's cache asynchronously?.

Once these are loaded, showing them on a click will be nearly instantaneous because they will come from the browser's cache (either memory or disk cache).

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Since you want your users to have a good experience on your site (and they don't get the 'slowish' impression), you should load the images asynchronously, but only after the current page has loaded (this is important, since you want your current page to be loaded fast).

That way your current page loads in the same time as before and you can also take advantage of pre-loading the images.

Look here to see how to load the images async (make sure you wrap that in a document.ready or something similar if you don't use jQuery):

Is there a way to load images to user's cache asynchronously?

Community
  • 1
  • 1
alessioalex
  • 62,577
  • 16
  • 155
  • 122