由于缓存,我的网页没有加载变化

My webpage doesn't load changes due to cache

本文关键字:网页 加载 变化 我的 于缓存 缓存      更新时间:2023-09-26

我试过使用现代web浏览器的缓存功能,但是它工作得太好了。我可以使浏览器重新缓存数据的唯一方法是修改manifest文件。

当然,我可以在清单文件中添加一个带有版本号的注释来强制浏览器,但是所需的手工工作感觉像是一个丑陋的hack。没有别的办法了吗?

我试着使用:

var loadNewCache = function() {
            window.addEventListener('load', function(e) {
                window.applicationCache.addEventListener('updateready', function(e) {
                    var newUpdates = (window.applicationCache.status == window.applicationCache.UPDATEREADY);
                    if (newUpdates) {
                        window.applicationCache.swapCache();
                        window.location.reload();
                    }
                }, false);
            }, false);
        };

但是这些事件永远不会被触发。

我在谷歌AppEngine上运行,并在我的app.yaml中有这个

- url: /html_client/(.*'.appcache)
  mime_type: text/cache-manifest
  static_files: html_client/'1
  upload: html_client/(.*'.appcache)

编辑

我让它与这个脚本一起工作,这个脚本作为前置部署运行。它不漂亮,但它有效。

#!/usr/bin/python
def main():
    """
    Takes the current git sha id and replaces version tag in manifest file with it.
    """
    from subprocess import Popen, PIPE
    input_file = open("manifest.appcache", 'r')
    output_file = open("manifest.appcache.tmp", 'w')
    try:
        git_sha_id = Popen(["git rev-parse --short HEAD"], stdout=PIPE, shell=True).communicate()[0]
        target_line = "# Version: "
        for line in input_file:
            if target_line not in line:
                output_file.write(line)
            else:
                output_file.write(target_line + git_sha_id)
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
    finally:
        input_file.close()
        output_file.close()
        Popen(["mv -f manifest.appcache.tmp manifest.appcache"], stdout=PIPE, shell=True)
if __name__ == "__main__":
    main()

您不需要做任何难看的事情,也不需要更改manifest文件。

你所需要做的就是在加载静态文件的url的末尾添加应用程序的当前版本。这个版本号会随着每次部署而改变,所以它会在每次新部署后被缓存。

<link rel="stylesheet" href="/static/css/main.css?{{VERSION}}" type="text/css" />

其中{{VERSION}}在生产环境中可能是os.environ.get('CURRENT_VERSION_ID', ''),在本地运行时可能只是一个随机数。

您可以检查您是否使用os.environ.get('SERVER_SOFTWARE','')在本地运行。这里有一个简单的例子来获取这个值,稍后您应该将其传递给您的基模板:

import random
import os
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
  VERSION = random.random()
else:
  VERSION = os.environ.get('CURRENT_VERSION_ID', '')