【发布时间】:2010-09-23 14:07:04
【问题描述】:
让浏览器使用缓存版本的 js 文件(来自服务器端)的最佳方法是什么?
【问题讨论】:
标签: javascript http caching
让浏览器使用缓存版本的 js 文件(来自服务器端)的最佳方法是什么?
【问题讨论】:
标签: javascript http caching
或在 .htaccess 文件中
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
【讨论】:
我刚刚完成了我的周末项目cached-webpgr.js 它使用 localStorage / web 存储来缓存 JavaScript 文件。这种方法非常快。我的小测试显示
实现这一点的代码很小,你可以在我的 Github 项目https://github.com/webpgr/cached-webpgr.js查看它
这是一个如何使用它的完整示例。
完整的库:
function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};
调用库
requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
requireScript('examplejs', '0.0.3', 'example.js');
});
【讨论】:
来自 PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
为我工作。
作为开发人员,您可能很快就会遇到不想要缓存文件的情况,在这种情况下请参阅Help with aggressive JavaScript caching
【讨论】:
在您的 Apache .htaccess 文件中:
#Create filter to match files you want to cache
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>
我也在这里写过:
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/
【讨论】:
我很想将其作为重复项关闭;这个问题似乎在整个网站上以许多不同的方式得到了回答:
【讨论】:
最好的(也是唯一的)方法是设置正确的 HTTP 标头,特别是这些标头:“Expires”、“Last-Modified”和“Cache-Control”。具体如何操作取决于您使用的服务器软件。
在Improving performance… 中查找“服务器端优化”以获取一般注意事项和相关链接,并查找“客户端缓存”以获取特定于 Apache 的建议。
如果你和我一样是nginx(或nginx in plain English)的粉丝,你也可以轻松配置:
location /images {
...
expires 4h;
}
在上面的示例中,来自 /images/ 的任何文件都将在客户端缓存 4 小时。
现在,当您知道要查找的正确词(HTTP 标头“Expires”、“Last-Modified”和“Cache-Control”)时,只需仔细阅读您使用的 Web 服务器的文档即可。
【讨论】:
我有一个纯 JavaScript 的简单系统。它检查从不缓存的简单文本文件中的更改。当您上传新版本时,此文件会更改。只需将以下JS放在页面顶部即可。
(function(url, storageName) {
var fromStorage = localStorage.getItem(storageName);
var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000));
getUrl(function(fromUrl) {
// first load
if (!fromStorage) {
localStorage.setItem(storageName, fromUrl);
return;
}
// old file
if (fromStorage === fromUrl) {
return;
}
// files updated
localStorage.setItem(storageName, fromUrl);
location.reload(true);
});
function getUrl(fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", fullUrl, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === XMLHttpRequest.DONE) {
if (xmlhttp.status === 200 || xmlhttp.status === 2) {
fn(xmlhttp.responseText);
}
else if (xmlhttp.status === 400) {
throw 'unable to load file for cache check ' + url;
}
else {
throw 'unable to load file for cache check ' + url;
}
}
};
}
;
})("version.txt", "version");
只需将“version.txt”替换为您始终运行的文件,将“version”替换为您要用于本地存储的名称。
【讨论】: