Is it possible to insert images in cache before rendering

前端 未结 3 437
傲寒
傲寒 2020-12-19 22:06

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 m

相关标签:
3条回答
  • 2020-12-19 22:34

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

    0 讨论(0)
  • 2020-12-19 22:48

    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.

    0 讨论(0)
  • 2020-12-19 22:52

    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);
    
    0 讨论(0)
提交回复
热议问题