目前我使用一个PHP脚本将多个CSS文件合并成一个脚本,然后以text/css的内容类型输出它们。
问题在于浏览器不会缓存该文件。
是否有更好的方法来解决这个问题?
谢谢。
<?php
header('Cache-control: max-age=3600'); // cache for at least 1 hour
header('Content-type: text/css');
readfile('css1.css');
readfile('css2.css');
etc...
我使用下面发布的代码。
它遵循谷歌页面速度建议。
请注意,readfile
比 include
更快,因此应该使用。
<?php
#$off = 0; # Set to a reasonable value later, say 3600 (1h);
$off = 604800; # Set to 1 week cache as suggested by google
$last_modified_time = filemtime('csscompressor.php');
$etag = md5_file('csscompressor.php');
ob_start("ob_gzhandler");
ob_start("compress");
header('Content-type: text/css; charset="utf-8"', true);
header("Cache-Control: private, x-gzip-ok=''");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT");
// load css files
readfile("global.css");
readfile('jquery-theme.css');
// ...
?>
你还应该像这样提供所有的CSS和JAVASCRIPT页面:
<script src="http://example.com/myjavascript.js?v=<?=$version=?>" ></script>
$version
变量由您控制。它应该在整个站点的配置文件中设置。每次您将更新推送到线上,您只需更改一个地方的版本,所有看到新内容的人都会直接推送它,而不依赖缓存。LINK
),而不是将它们内嵌。