我注意到一些浏览器(特别是Firefox和Opera)非常热衷于使用.css和.js文件的缓存副本,甚至在浏览器会话之间。当您更新其中一个文件时,这会导致一个问题,但用户的浏览器会继续使用缓存的副本。
当文件发生更改时,强迫用户浏览器重新加载文件的最优雅的方法是什么?
理想情况下,该解决方案不会强制浏览器在每次访问页面时重新加载文件。
我发现John Millikin和da5id的建议很有用。这有一个专门的术语:自动版本控制。
我在下面发布了一个新的答案,这是我最初的解决方案和约翰的建议的结合。
SCdF建议的另一个想法是将伪查询字符串附加到文件中。(一些自动使用时间戳作为伪查询字符串的Python代码是由pi..提交的)
然而,关于浏览器是否缓存带有查询字符串的文件还存在一些讨论。(请记住,我们希望浏览器缓存该文件并在以后的访问中使用它。我们只希望它在文件更改时再次获取该文件。)
对于Java Servlet环境,可以查看Jawr库。功能页面解释了它是如何处理缓存的:
Jawr will try its best to force your clients to cache the resources. If a browser asks if a file changed, a 304 (not modified) header is sent back with no content. On the other hand, with Jawr you will be 100% sure that new versions of your bundles are downloaded by all clients. Every URL to your resources will include an automatically generated, content-based prefix that changes automatically whenever a resource is updated. Once you deploy a new version, the URL to the bundle will change as well so it will be impossible that a client uses an older, cached version.
该库还可以简化JavaScript和CSS,但如果不需要,可以将其关闭。
这个解决方案是用PHP编写的,但是应该很容易适应其他语言。
原始的.htaccess正则表达式可能会导致json-1.3.js等文件出现问题。解决方案是只有在结尾恰好有10位数字时才重写。(因为10位数字涵盖了从2001年9月9日到2286年11月20日的所有时间戳。)
首先,我们在.htaccess中使用下面的重写规则:
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
现在,我们编写以下PHP函数:
/**
* Given a file, i.e. /css/base.css, replaces it with a string containing the
* file's mtime, i.e. /css/base.1221534296.css.
*
* @param $file The file to be loaded. Must be an absolute path (i.e.
* starting with slash).
*/
function auto_version($file)
{
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
return $file;
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
现在,无论你在哪里包含你的CSS,从下面更改它:
<link rel="stylesheet" href="/css/base.css" type="text/css" />
:
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />
这样,您就不必再次修改链接标签,用户将始终看到最新的CSS。浏览器将能够缓存CSS文件,但当您对CSS进行任何更改时,浏览器将看到这是一个新的URL,因此它不会使用缓存的副本。
这也适用于图像、favicons和JavaScript。基本上任何不是动态生成的东西。
只需使用服务器端代码添加文件的日期…这样,它将被缓存,只有当文件更改时才会重新加载。
在ASP。NET:
<link rel="stylesheet" href="~/css/custom.css?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath("~/css/custom.css")).ToString(),"[^0-9]", ""))" />
<script type="text/javascript" src="~/js/custom.js?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath("~/js/custom.js")).ToString(),"[^0-9]", ""))"></script>
这可以简化为:
<script src="<%= Page.ResolveClientUrlUnique("~/js/custom.js") %>" type="text/javascript"></script>
通过在项目中添加扩展方法来扩展Page:
public static class Extension_Methods
{
public static string ResolveClientUrlUnique(this System.Web.UI.Page oPg, string sRelPath)
{
string sFilePath = oPg.Server.MapPath(sRelPath);
string sLastDate = System.IO.File.GetLastWriteTime(sFilePath).ToString();
string sDateHashed = System.Text.RegularExpressions.Regex.Replace(sLastDate, "[^0-9]", "");
return oPg.ResolveClientUrl(sRelPath) + "?d=" + sDateHashed;
}
}
另一个关于ASP的建议。网的网站,
Set different cache-control:max-age values, for different static files.
For CSS and JavaScript files, the chances of modifying these files on server is high, so set a minimal cache-control:max-age value of 1 or 2 minutes or something that meets your need.
For images, set a far date as the cache-control:max-age value, say 360 days.
By doing so, when we make the first request, all static contents are downloaded to client machine with a 200-OK response.
On subsequent requests and after two minutes, we see 304-Not Modified requests on CSS and JavaScript files which avoids us from CSS and JavaScript versioning.
Image files will not be requested as they will be used from cached memory till the cache expires.
By using the below web.config configurations, we can achieve the above described behavior,
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00.00:01:00"/>
</staticContent>
<httpProtocol>
<customHeaders>
<add name="ETAG" value=""/>
</customHeaders>
</httpProtocol>
</system.webServer>
<location path="Images">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="180.00:00:00" />
</staticContent>
</system.webServer>
</location>
仅在纯JavaScript的本地开发中禁用script.js的缓存。
它会注入一个随机的script.js?Wizardry =1231234并阻塞常规script.js:
<script type="text/javascript">
if(document.location.href.indexOf('localhost') !== -1) {
const scr = document.createElement('script');
document.setAttribute('type', 'text/javascript');
document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());
document.head.appendChild(scr);
document.write('<script type="application/x-suppress">'); // prevent next script(from other SO answer)
}
</script>
<script type="text/javascript" src="scripts.js">
这里的许多答案主张向URL添加时间戳。除非直接修改生产文件,否则文件的时间戳不太可能反映文件更改的时间。在大多数情况下,这将导致URL比文件本身更频繁地更改。这就是为什么你应该使用文件内容的快速散列,如levik和其他人建议的MD5。
请记住,该值应该在构建或运行时计算一次,而不是在每次请求文件时计算一次。
例如,下面是一个简单的bash脚本,它从标准输入读取文件名列表,并将包含散列的JSON文件写入标准输出:
#!/bin/bash
# Create a JSON map from filenames to MD5 hashes
# Run as hashes.sh < inputfile.list > outputfile.json
echo "{"
delim=""
while read l; do
echo "$delim\"$l\": \"`md5 -q $l`\""
delim=","
done
echo "}"
然后,该文件可以在服务器启动时加载并引用,而不是读取文件系统。