如何在HTML文件的末尾添加自定义字符串以防止缓存

时间:2019-01-21 19:30:31

标签: javascript html html5 caching

我想防止文件缓存,所以我想在结尾添加JavaScript日期或ID代码?我将如何去做任何想法或建议表示赞赏!!!

我已经尝试了数小时的谷歌搜索并尝试了htaccess编辑

我尝试使用

编辑我的htaccess文件
<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>
AddType application/x-httpd-php .m3u .m3u8

但是不走运,所以我现在想找出答案...

所以我要它做的是说我有file.html,它将它转换为file.html?date&time或file.html?Randomid,所以它总是加载HTML文件的FRESH副本并且不缓存。用户不必每次更新都清除缓存,因为.html文件每隔几个小时更新一次,并且重要的是没有缓存...

像这样的事情是我的主意,但我无法使其工作

<script>
    function randString(n)
    {
        if(!n)
        {
            n = 5;
        }

        var text = '';
        var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        for(var i=0; i < n; i++)
        {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }

        return text;
    }
    </script>
    <iframe src="url.com/file.html?' + randString(4) })" style="border:0px #ffffff none;" name="fss" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="460px" width="640px" allowfullscreen></iframe>

1 个答案:

答案 0 :(得分:0)

在加载窗口时,抓取iframe并使用时间戳修饰符将其加载到src中。 getTime是一种返回自1970年以来的毫秒数的方法,因此您不必担心导线交叉。

iframe.src = "url.com/index.html?t=" + new Date().getTime();

let iframe = document.querySelector("iframe");
iframe.src = "url.com/index.html?t=" + new Date().getTime();

console.log(iframe);
<iframe></iframe>