Post-loading : check if an image is in the browser cache

后端 未结 6 2316
执笔经年
执笔经年 2020-12-02 22:57

Short version question : Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?

Long ve

6条回答
  •  情话喂你
    2020-12-02 23:54

    The most efficient, simple, and widely supported way to check if an image has already been cached is to do the following...

    1. Create an image object
    2. Set the src property to the desired url
    3. Check the completed attribute immediately to see if the image is already cached
    4. Set the src attribute back to "" (empty string), so that the image is not unnecessarily loaded (unless of coarse you want to load it at this time)

    Like so...

    function isCached(src) {
        var img = new Image();
        img.src = src;
        var complete = img.complete;
        img.src = "";
        return complete;
    }
    

提交回复
热议问题