简体   繁体   中英

Compressing CSS and JS without mod_gzip and mod_deflate

I would like to compress the CSS and JS files on my server to minimise load times, problem.

My hosting is with Streamline.net (big mistake, never go there) who will not activate mod_gzip and mod_deflate due to security issues.

Does anyone have another way to compress these types of files (and image files too if poss) without going the way of mod_gzip and mod_deflate.

Answers would be hugely welcome.

Yes, the answer is Minification .

Obviously, it will not compress as much as gzip or deflate . But it helps, and it is very easy to do with the right tools.

You can run your files through a script which would gzip them for you and add appropriate expiration headers. Either set up an URL rewrite, or rewrite the URLs manually:

<script src="js/somescript.js"></script>

becomes

<script src="compress.php?somescript.js"></script>

and in compress.php, you can do something like

<?php
$file = 'js/' . basename($_SERVER['QUERY_STRING']);
if (file_exists($file)) {
    header ('Last-Modified: ' . date('r',filemtime($file));
    header ('Content-Type: text/javascript'); // otherwise PHP sends text/html, which could confuse browsers
    ob_start('ob_gzhandler');
    readfile($file);
} else {
    header('HTTP/1.1 404 Not Found');
}

Obviously this can be extended to also provide HTTP caching , and/or on-the-fly minification, further speeding up your visitors' browsing.

Instead of getting mod_gzip to gzip your CSS and JavaScript files dynamically, you can gzip them yourself, then upload them.

This does introduce another step before you upload CSS and JavaScript, but it works, and maybe even saves a tiny bit of server processing time for each request compared to mod_gzip.

On Mac OS X, gzipping a file on the command line is as easy as, eg:

gzip -c styles.css > styles-gzip.css

Make sure these files get served with the right content-type header though.

正如旁注:压缩图像如果已经以压缩格式保存并且最大压缩对用户来说仍然很好,那么压缩图像将不会有益。

Most programming languages support some data or file compression formats like ZLIB or GZIP. So you could use a programming language to compress your files with one of these formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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