1

So I have a site with a 3 pages that have very rich backgrounds, and I would like to know if it is possible to cache images manually via AJAX on the hompage, so that when a use goes to a new page, the large image is already loaded.

I'm using rails/turbolinks. I know there must be a way, but I was wondering if anyone knows the best practices.

OneChillDude
  • 7,856
  • 10
  • 40
  • 79

2 Answers2

3

Here is how you could solve your problem:

JavaScript: There is a quite good article called Simple Asset Management who describes a very good pre-load mechanism. It's very recommended to use it when you have a huge list of assets and you can't just download it all at once.

CSS: There is also CSS technique that you describe all images that you want to preload at your CSS and leave the browser with the rest.

HTM5: If you need a HTML5 approach, HTML5 already has a new attribute called rel="prefetch":

<link rel="prefetch" href="http://asset.to.prefetch/imgs/sprite.png" />

More about HTML5 rel prefetch

Hope it helps.

Community
  • 1
  • 1
Igor Escobar
  • 1,047
  • 1
  • 12
  • 13
2

Yes, it's possible.

Use after page load event (to avoid the cache images slow down the current page speed time) a $.load function, like this:

$(document).load(function() {
    $.load("www.domain.com.br/img/image-to-pre-cache.jpg");
});

This should work... but, if does not work, you can also use

$(document).load(function() {
    $('<img/>')[0].src = "www.domain.com.br/img/image-to-pre-cache.jpg";
});
Elias Soares
  • 9,884
  • 4
  • 29
  • 59