简体   繁体   English

组合多个CSS文件

[英]Combining multiple CSS files

Right now I use a PHP script to pull together multiple CSS files into one script and then output them with a content-type of text/css. 现在我使用PHP脚本将多个CSS文件合并到一个脚本中,然后使用内容类型的text / css输出它们。

The problem them with this is the browser wont cache the file. 他们的问题是浏览器不会缓存文件。

Is there a better way of doing this? 有没有更好的方法呢?

Thanks 谢谢

If you have to serve the CSS via PHP, you can force a cache header to be emitted, so the browser can cache the output if it so desires: 如果你必须通过PHP提供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...

Why don't you just use @import in a global css file and link that into your html file? 为什么不在全局css文件中使用@import并将其链接到您的html文件中?

see: http://www.cssnewbie.com/css-import-rule/ 见: http//www.cssnewbie.com/css-import-rule/

"Cascading style sheets" are so called before CSS files may include others. 在CSS文件可能包含其他文件之前,所谓的“层叠样式表”。 You can also specify several CSS files in your HTML file (using LINK ) instead of including them inline. 您还可以在HTML文件中指定多个CSS文件(使用LINK ),而不是将它们包含在内。

Use these facilities and let your web server take care of sending the appropriate headers for client-side caching an handling of conditional HTTP requests. 使用这些工具,让您的Web服务器负责发送适当的标头,以便客户端缓存处理条件HTTP请求。

I use the code posted bellow. 我使用下面发布的代码。

It follows Google's page speed recommendations. 它遵循谷歌的页面速度建议。

Do notice that readfile is faster that include so should be used. 请注意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');
// ...

?>

You should also serve all CSS and JAVASCRIPT pages like this: 您还应该像这样服务所有CSS和JAVASCRIPT页面:

<script src="http://example.com/myjavascript.js?v=<?=$version=?>" ></script>

The $version variable is controlled by you. $version变量由您控制。 It should be set in a site-wide config file. 它应该在站点范围的配置文件中设置。 Every time you push an update live you can just change the version on one place and everyone seeing the new content will just push it and not depend on cache. 每次推送更新时,您只需在一个地方更改版本,每个看到新内容的人都会推送它而不依赖于缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM