在javascript中加载json数据文件并避免缓存

时间:2017-06-17 09:24:52

标签: javascript browser-cache

如何在我的javascript文件中加载JSON文件,并确保如果我在用户查看我的网站时更新JSON文件,它将始终使用最新版本而不使用缓存版本?

在我的javascript中说我加载了一个像这样的JSON数据文件的文件:

 // Create a <script> tag and set the USGS URL as the source.
        var script = document.createElement('script');
        // This example uses a local copy of the GeoJSON stored at
        // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
        script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
        document.getElementsByTagName('head')[0].appendChild(script);

如果远程文件发生更改,我如何确保它始终加载最新版本的文件而不是由浏览器缓存?

2 个答案:

答案 0 :(得分:1)

您可以尝试在XHR中使用»如果修改后的«标题。基本上您请求相同的文件,但添加了if-modified-since: <some date from the past>标头。如果文件已更改,则会获得200状态加上内容,否则标题中的304状态代码为无内容。但服务器必须支持这一点,但在这种情况下(google api),我想这应该可行。

source

答案 1 :(得分:-1)

您可以插入src的实际时间戳 script.src + ='?v ='+ Date.now();

相关问题