How to force a web browser NOT to cache images

后端 未结 17 883
太阳男子
太阳男子 2020-11-22 13:51

Background

I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML

17条回答
  •  爱一瞬间的悲伤
    2020-11-22 14:23

    You must use a unique filename(s). Like this

    
    

    But this technique means high server usage and bandwidth wastage. Instead, you should use the version number or date. Example:

    
    

    But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.

    
    

    However, it is still not effective. Reason: Browser cache ... The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.

    var items = document.querySelectorAll("img.NO-CACHE");
    for (var i = items.length; i--;) {
        var img = items[i];
        img.src = img.src + '?' + Date.now();
    }
    

    USAGE

    
    

    RESULT(s) Like This

    https://example.com/image.png?1582018163634
    

提交回复
热议问题