3

I am using ColdFusion 10 and jQuery 1.7.1 and Bootstrap.

I am developing a web site that has a lot of large, high-quality images on the home page. On the home page, there is an image carousel that pulls ten high quality images from a database. The images can be 1 meg each. The carousel images aren't my problem (right now), but it has something to do with it.

The problem I am trying to address right now is that I use a high quality background image that I want to continue using, it's about 180k. If I have the background in cache on the home page, I want to use it. If not, then I don't want to use it on the home page. I'll load it from a different page. When the user returns to the home page, and the background image is in cache, I want to use it.

Can I test whether an image is already in cache and if so, dynamically load or NOT load based on that?

You can see the home page here:

http://flyingpiston2012-com.securec37.ezhostingserver.com/

2 Answers 2

1

I don't think that there is a way to test if an image is in your browser cache.

However, one way that you could solve this problem is by using jQuery's .load() event. When an image is loaded, put the image ID (or filename) into localStorage (or a cookie). You can then test this variable to see if the image has been loaded.

Example of setting the localStorage variable for your images:

$(document).ready(function () {
   $('.hiResImg').load(function () {
      var imgSrc = $(this).attr('src');
      var loadedImgs = localStorage.getItem("loadedImgs");

      loadedImgs = loadedImgs || [];

      loadedImgs.push(imgSrc);

      localStorage.setItem("loadedImgs", loadedImgs);
   });
});

Example of testing for and loading the image:

$(document).ready(function () {
   var loadedImgs = localStorage.getItem("loadedImgs").split(',');

   var imagePath = "http://localhost/path/to/someImg.jpg";

   if ($.inArray(imagePath, loadedImgs) > -1) {
      $('body').css('background-image', 'url(' + imagePath + ')');
   }
});

Note: this code has not been fully tested.

1
  • 1
    That sounds like a good idea! I think I will move forward with this approach.
    – Evik James
    Aug 14, 2012 at 14:26
0

It may or may not be an option depending on the browser support you requre, but you could store it in the browser's localStorage using a DataURL.

Here's a Mozilla article covering this topic: http://hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/

You should also be aware that localStorage does have a size limit, which I believe is typically 5MB for a given domain. This shouldn't be an issue with your 180KB background image, but depending on browser settings and other pages/sites on the domain there is the chance it may be an issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.