3

I have this webpage which shows me some images and some images are on a mouseover event and hence it takes time for them to display. I have worked it around by placing the mouseover image and hidding them through display none property which puts them in browsers cache and display them quickly on mouseover.I was thinking that is it possible to insert the images into cache of a browser by another way like using jQuery or something so i dont have to put images in hidden form.

I dont know if this is a stupid question.

Please comment.

Regards Himanshu Sharma

techie_28
  • 2,123
  • 4
  • 41
  • 62

3 Answers3

7

You can preload images which will cause them to be in the cache so they are available immediately for things like mouse events. See this post for sample code that pre-caches an array of images.

function preloadImages(srcs) {
    if (!preloadImages.cache) {
        preloadImages.cache = [];
    }
    var img;
    for (var i = 0; i < srcs.length; i++) {
        img = new Image();
        img.src = srcs[i];
        preloadImages.cache.push(img);
    }
}

// then to call it, you would use this
var imageSrcs = ["src1", "src2", "src3", "src4"];

preloadImages(imageSrcs);
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • we can access the cache using .cache? – techie_28 Jan 12 '12 at 07:26
  • @techie_28 - I don't understand your question. This code creates image objects with your image URLs loaded into them. That process causes the browser to cache the images so that when those images URLs are used elsewhere in your page, they are loaded immediately from the browser cache. After preloading them, you just use the URLs normally and the browser will automatically fetch them from the cache. You don't access the cache yourself - the browser does it for you. – jfriend00 Jan 12 '12 at 07:30
  • my question was what is .cache property here? – techie_28 Jan 12 '12 at 07:32
  • 1
    @techie_28 - The `.cache` property is just an array of image objects where the image objects are stored so they can load their images. It's a property on the function to avoid creating another global variable. – jfriend00 Jan 12 '12 at 07:34
3

You can just use (new Image).src="http://path/to/img.jpg" which will make the browser load it

Adam Heath
  • 4,703
  • 2
  • 35
  • 50
1

First of all, use sprites for small and/or 'mouseover' images. Also, yes, you can preload images with javascript, but remember about page load sequence, so it might not be faster then css.

YuS
  • 2,025
  • 1
  • 15
  • 24