通过gzip压缩js、css文件,并在客户端缓存

文章分类:PHP  查看次数:658 + 123

从国外的一篇文章中看到的,具体地址忘了,如果有哪位仁兄知道,还望告知,谢谢

之前我也提到过通过gzip来压缩js文件,但是那种方法有不少的缺点,比如不能在客户端缓存,所以每次都需要通过服务端压缩,这是很耗CPU的。

现在这个方法虽不能说是最好的,但性价比是非常高的。特点:

  • 只在服务端压缩一次,前提是文件没有人为更新
  • 在客户端缓存(IE,FF)
  • 可以非常方便地压缩所有调用的

是不是挺不错的,下面来看看实现方法,以ext为例。(要求配置为apache+php,apache开启mod_rewrite,php开启zlib)
先是在根目录下建一个.htaccess文件

RewriteEngine On
RewriteRule (.*.|.*.) compress.php?f=$1 [L]
 

然后构建compress.php(先在根目录下建一个cache文件夹)
compress.php代码

<?php

    // setting variables
    $cache = true;
    $cachedir = 'cache';
   
    // Determine the directory and file extension
    $fn = $_GET['f'];
    $t = explode('.', $fn);
    $ext = $t[count($t)-1];
    switch($ext) {
        case '':
            $type = '';
        break;
        case '':
            $type = 'javascript';
        break;
    }
   
    $base = dirname($fn);
   
    // Determine last modification date of the files
    $lastmodified = filemtime($fn);
   
    // Send Etag hash
    $hash = $lastmodified . '-' . md5($fn);
    header ("Etag: \"" . $hash . "\"");
   
    if (
        isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
        stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) == '"' . $hash . '"'
    ){
        // Return visit and no modifications, so do not send anything
        header ("HTTP/1.0 304 Not Modified");
        header ('Content-Length: 0');
    } else {
        // First time visit or files were modified
        if ($cache) {
            // Determine supported compression method
            $ = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], '');
            $deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate');

            // Determine used compression method
            $encoding = $ ? '' : ($deflate ? 'deflate' : 'none');

            // Check for buggy versions of Internet Explorer
            if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Opera') &&
                preg_match('/^Mozilla\/4\.0 \(compatible; MSIE ([0-9]\.[0-9])/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
                $version = floatval($matches[1]);
               
                if ($version < 6)
                    $encoding = 'none';
                   
                if ($version == 6 && !strstr($_SERVER['HTTP_USER_AGENT'], 'EV1'))
                    $encoding = 'none';
            }
           
            // Try the cache first to see if the compressed file is already generated
            $cachefile = 'cache-' . $hash . '.' . str_replace('/', '-', $fn) . ($encoding != 'none' ? '.' . $encoding : '');

            if (file_exists($cachedir . '/' . $cachefile)) {
                if ($fp = fopen($cachedir . '/' . $cachefile, 'rb')) {

                    if ($encoding != 'none') {
                        header ("Content-Encoding: " . $encoding);
                    }
               
                    header ("Content-Type: text/" . $type);
                    header ("Content-Length: " . filesize($cachedir . '/' . $cachefile));
       
                    fpassthru($fp);
                    fclose($fp);
                    exit;
                }
            }
        }

        // Get contents of the files
        $content = file_get_contents($fn);
        // Send Content-Type
        header ("Content-Type: text/" . $type);
       
        if (isset($encoding) && $encoding != 'none') {
            //Send compressed contents
            $content = gzencode($content, 9, $ ? FORCE_GZIP : FORCE_DEFLATE);
            header ("Content-Encoding: " . $encoding);
            header ('Content-Length: ' . strlen($content));
            echo $content;
        } else {
            // Send regular contents
            header ('Content-Length: ' . strlen($content));
            echo $content;
        }

        // Store cache
        if ($cache) {
            if ($fp = fopen($cachedir . '/' . $cachefile, 'wb')) {
                fwrite($fp, $content);
                fclose($fp);
            }
        }
    }    
?>
 

大功告成!如果成功调用的话,会在cache下生成一些文件。

评论

共4 条评论 to “通过gzip压缩js、css文件,并在客户端缓存”

  1. CHI on 2007-11-27 4:54 pm
    Gravatar

    想在贵BLOG做广告 如有意请加QQ:556386谢谢

    [回复此评论]

  2. lzyy on 2007-11-27 7:19 pm
    Gravatar

    不好意思,最近还没有做广告的意向

    [回复此评论]

  3. fzx on 2007-12-28 1:33 pm
    Gravatar

    作者能讲解具体实现原理吗?

    [回复此评论]

  4. lzyy on 2008-01-03 6:01 pm
    Gravatar

    主要就是通过判断header,来决定是否输出压缩后的文件

    [回复此评论]

发表评论