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

后端 未结 1 670
刺人心
刺人心 2020-11-28 16:34

I have a list of items. Each of them is a square with a name, and when user hover on the square, an image will show, which is done by jQuery. Code is like this:



        
相关标签:
1条回答
  • 2020-11-28 17:22

    You can preload images like this:

    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);
    

    Just fill in the URLs in the imageSrcs array and run this when your page first runs. The sooner you run it, the earlier your images will be available.

    FYI, a related answer here: Image preloader javascript that supports events.

    0 讨论(0)
提交回复
热议问题