所谓的压缩,无非就是把换行空格等符号替换为空

  • 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文件下的 ./test.css include('第二个CSS文件'); //复制调用更多css文件 ./test1.css ob_end_flush(); //浏览器打开,输出压缩后的内容 ?>
  • js
<?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(); //输出压缩后的内容 } ?>
Last modification:September 8, 2023
如果觉得我的文章对你有用,请随意赞赏