开发者

Combining multiple CSS files

开发者 https://www.devze.com 2023-01-11 03:31 出处:网络
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.

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.

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

    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?

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


"Cascading style sheets" are so called before CSS files may include others. You can also specify several CSS files in your HTML file (using LINK) instead of including them inline.

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.


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.

<?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:

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

The $version variable is controlled by you. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消