scz*_*vos 1 css php caching browser-cache
我的想法很简单,在一些css文件中更改所有css文件并生成一个缩小的文件.然后告诉浏览器清除缓存.如果浏览器缓存中存在未更改的文件,则使用它 - 因此用户无需每次都重新下载.
我正在使用以下代码段来执行此操作.但是使用缓存的部分有点错误,大部分时间它都有效,但有时它会告诉浏览器使用缓存版本(因为没有变化),浏览器使用旧版本,用户必须进行客户端缓存刷新.
你能给我一些建议怎么做,所以每当发生变化时它会刷新客户端浏览器缓存,如果没有变化就只使用缓存?
$cssFiles = getCssFiles();
$fm = new FileMinifier(FileMinifier::TYPE_CSS);
$lastModified = $fm->lastModification($cssFiles);
$savedLastModified = DateUtils::convertToTimestamp($this->system->systemSettings['cssLastChange']);
$etagFile = md5('css-file');
header("Content-type: text/css");
header("Pragma: public");
header('Cache-Control: public');
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModified) . " GMT");
header("Etag: $etagFile");
// if there is a change - generate new minified css
if ($lastModified > $savedLastModified)
{
// take files minify them, save it and redirect to output, update last change time
...
}
// or use already generated
else
{
$ifModifiedSince = (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : 0);
$etagHeader = (isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
// if it is in chache use it! - no need for redownloading
if (strtotime($ifModifiedSince) == $lastModified || $etagHeader == $etagFile)
{
header("HTTP/1.1 304 Not Modified");
exit;
}
$this->data['text'] = file_get_contents(SystemInfo::getServerRoot() . '/public/css/minified.css');
}
Run Code Online (Sandbox Code Playgroud)
你要做的是令人钦佩的,但它有点重新发明轮子.就CSS文件,JavaScript文件等而言,现代浏览器已经很好地从缓存中提取未更改的文件.
操纵HTTP标头以通知浏览器文件更改是可行的,但是标题的解释方式存在浏览器差异(尤其是旧浏览器),这使得该方法充满了细微差别.
这是迄今为止容易通过你的版本包括CSS来实现你的目标.文件版本的更改将提示浏览器重新下载文件.
例:
在更改文件之前:
<link href="http://yourwebsite.com/file.css?_=1.0.0.1" rel="stylesheet" type="text/css">
Run Code Online (Sandbox Code Playgroud)
文件更改后:
<link href="http://yourwebsite.com/file.css?_=1.0.0.2" rel="stylesheet" type="text/css">
Run Code Online (Sandbox Code Playgroud)
所有浏览器都会将URI参数中的更改解释为新文件,并将重新下载.
也可以自动化版本控制,这样您就不需要在每次更改后手动编辑包含行.这是一种方法......
例:
<?php
$ver = filemtime($filename);
echo '<link href="http://yourwebsite.com/file.css?_='.$ver.'" rel="stylesheet" type="text/css">';
?>
Run Code Online (Sandbox Code Playgroud)
该代码将文件的附加修改日期(Unix时间戳格式)附加到文件include的URI.