Best way to compress HTML, CSS & JS with mod_deflate and mod_gzip disabled

前端 未结 5 1864
轻奢々
轻奢々 2021-02-20 17:48

I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod_d

5条回答
  •  花落未央
    2021-02-20 18:18

    what ever you do, be careful about caching on the client side:

    Browsers do all sort of tricks to try and minimize the bandwith and there are many ways in the HTTP protocol to do that, all of which are dealt with by apache - if you are just serving a local file.

    If you are not, then it's your responsibility.

    Have a look at least at the ETag and the If-Modified-Since mechanics which are supported by all current browsers and seem to be the most robust way to query the server for updated content.

    A possible way to serve a CSS file to browsers using the If-Modified-Since-Header is something like this (the empty headers to turn off any non-caching headers PHP sends per default):

    $p = 'path/to/css/file'
    $i = stat($p);
    if ($_SERVER['HTTP_IF_MODIFIED_SINCE']){
        $imd = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
        if ( ($imd > 0) && ($imd >= $i['mtime'])){
            header('HTTP/1.0 304 Not Modified');
            header('Expires:');
            header('Cache-Control:');
            header('Last-Modified: '.date('r', $i['mtime']));
            exit;
        }
    }
    header('Last-Modified: '.date('r', $i['mtime']));
    header('Content-Type: text/css');
    header('Content-Length: '.filesize($p));
    header('Cache-Control:');
    header('Pragma:');
    header('Expires:');
    readfile($p);
    

    The code will use the if-modified-since-header the browser sends to check if the actual file on the server has changed since the date the browser has given. If so, the file is sent, otherwise, a 304 Not Modified is returned and the browser does not have to re-download the whole content (and if it's intelligent enough, it keeps the parsed CSS around in memory too).

    There is another mechanic involving the server sending a unique ETag-Header for each piece of content. The Client will send that back using an If-None-Match header allowing the server to decide not only on the date of last modification but also on the content itself.

    This just makes the code more complicated though, so I have left it out. FF, IE and Opera (probably Safari too) all send the If-Modified-Since header when they receive content with a Last-Modified header attached, so this works fine.

    Also keep in mind that certain versions of IE (or the JScript-Runtime it uses) still have problems with GZIP-transferred content.

    Oh. And I know that's not part of the question, but so does Acrobat in some versions. I've had cases and cases of white screens while serving PDFs with gzip transfer encoding.

提交回复
热议问题