【问题标题】:My webpage doesn't load changes due to cache由于缓存,我的网页无法加载更改
【发布时间】:2013-06-10 11:57:13
【问题描述】:

我尝试过使用现代网络浏览器的缓存功能,但效果太好了。让浏览器重新缓存数据的唯一方法是修改清单文件。

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

我尝试过使用:

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);
        };

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

我在 Google 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()

【问题讨论】:

  • 我认为this is one of the gotchas for the app cache 和更新清单是唯一的方法。
  • 你说的是css、js之类的文件吗?
  • @JosephtheDreamer 所以你是说我必须为我想要测试的每一个更改手动调整清单文件?那么所有这些附加到 applicationCache 的 eventListener 有什么意义呢?

标签: javascript html google-app-engine google-chrome html5-appcache


【解决方案1】:

您无需做任何丑陋的事情并更改清单文件。

您需要做的就是在您正在加载静态文件的 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', '')

【讨论】:

  • 这听起来很有希望,我会尝试一下,谢谢。 :) 一些问题: - 这是处理开发和缓存的“正确”方式吗? - 我读过的事件监听器能以编程方式检测缓存更改的意义何在?
猜你喜欢
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2021-12-29
相关资源
最近更新 更多