极
极核实验室

Compress CSS and JS Output with PHP

AI summary
文章介绍了通过PHP脚本压缩网站CSS和JavaScript文件的方法,以提升运行速度。主要内容包括使用PHP读取并合并多个CSS或JS文件,通过正则表达式和字符串替换去除不必要的空格、换行和注释,实现代码压缩。同时展示了如何设置HTTP头信息,包括内容类型、缓存控制和过期时间,并利用zlib扩展进行gzip压缩。文章强调压缩后的代码能够显著提高页面加载速度,建议将前端链接指向处理后的PHP文件。

Repost license

Request authorization before reposting and retain the authorization code, original URL, and go/affiliate links.

Original URL:https://www.geekcorelab.com/post/using-php-to-compress-css-and-js-output

The commercial link is an authorized go short link that must stay on the reposted page. It records the source before sending readers to the original article.

Recently I found that compressing the website's CSS and JavaScript makes it run much faster
Let me share the code: use PHP to process and compress all CSS and JS into a single file for output

CSS

<?php  
    header('Content-type: text/css');  
    ob_start("compress");  
    function compress($buffer) {  
        $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);  
        $buffer = str_replace(array(" 
        ", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);  
        return $buffer;  
    }  
    include('第一个CSS文件');   //例如当前PHP文件下的 ./main.js
    include('第二个CSS文件');   //复制调用更多JS文件
    ob_end_flush();  //输出压缩后的内容
?>

Just change the file path and it is ready to use
For frontend CSS linking, just link directly to the PHP file

 <link rel="stylesheet" type="text/css" href="处理CSS的PHP文件"/>

JavaScript

<?php
    error_reporting(E_ALL & ~E_NOTICE);
    if(extension_loaded('zlib')){
        ob_start('ob_gzhandler');
    }
    header ("content-type:application/x-javascript; charset: UTF-8");
    header ("cache-control: must-revalidate");
    $offset = 60 * 60 * 24; //js文件的距离现在的过期时间,这里设置为一天
    $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
    header ($expire);
    ob_start("compress");
    function compress($buffer) {
        $buffer = preg_replace('/\/\/.*/','', $buffer);
        $buffer = str_replace(array("
        ", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
        return $buffer;
    }
    include('js文件一'); //例如当前PHP文件下的main.js
    include('js文件二'); //复制调用更多JS文件
    if(extension_loaded('zlib')){
        ob_end_flush(); //输出压缩后的内容
    }
?>

Similarly, just modify the file

<script src="处理JS的PHP文件" type="text/javascript" charset="utf-8"></script>

After compression, the speed will be much faster

Comments

Discussion

Be kind and keep the discussion friendly.

Complete your profile details to improve the chance of approval.

Your email will not be shown publicly.

Loading...

Markdown supported.

Discussion

0 comments

Internal link graph

Loading internal links…

View linked articles