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.
Discussion
0 comments