压缩html的起因
有人询问higrid如何压缩html,也就是说能不能把所有的html、js、css在运行前都压缩成一行,清除注释标记、换行符、空格、制表符等。
这样一个直接的好处是 减小html页面体积来提高前端加载速度。
很多人认为启动gzip,但一般启动gzip都比较少对html启动gzip压缩,因为现在的html都是动态的,不会使用浏览器缓存,而启用gzip的话每次请求都需要压缩,会比较消耗服务器资源,对js,css启动gzip比较好是因为js,css都会使用缓存。
而大家也用了很多软件过滤一下压缩,也有在线js/css/html压缩工具,higrid觉得也很麻烦,可读性很差。
采用php来压缩html
/** * 压缩html : 清除换行符,清除制表符,去掉注释标记 * @param $string * @return压缩后的$string * */function compress_html($string){ $string=str_replace("\r\n",'',$string);//清除换行符 $string=str_replace("\n",'',$string);//清除换行符 $string=str_replace("\t",'',$string);//清除制表符 $pattern=array( "/> *([^ ]*) *</",//去掉注释标记 "/[\s]+/", "/<!--[^!]*-->/", "/" /", "/ "/", "'/\*[^*]*\*/'" ); $replace=array ( ">\\1<", " ", "", """, """, "" ); return preg_replace($pattern, $replace, $string); }
php来压缩html注意事项
php来压缩htm 实现的方式主要是用正则表达式去查找,替换。在html压缩的时候,主要要注意下面几点:
1.html 文档中,多个空白字符等价为一个空白字符。也就是说换行等空白字符的删除是不安全的,有可能导致部分元素的样式产生差异。
2.html中有一个pre, 表示 preformatted text. 里面的任何空白,都不能被删除,因此pre,textarea 标签里面的内容格式需要保留,不能压缩。
3.html 中有可能有 ie 条件注释。这些条件注释是文档逻辑的一部分,不能被删除。因此去掉html注释的时候,有些注释是不能去掉的,比如:
4.压缩嵌入式js中的注释要注意,因为可能注释符号会出现在字符串中,比如: var url = “https://www.99zyku.com/Upload/Articles/1/0/306/306685_20210728185921235.net”; // 前面的//不是注释
5.对于动态页面来说,html 的压缩有可能还会增加服务器的 cpu 负担,得不偿失
个人使用的php压缩html函数代码
function higrid_compress_html($higrid_uncompress_html_source ) { $chunks = preg_split( '/(<pre.*?/pre>)/ms', $higrid_uncompress_html_source, -1, preg_split_delim_capture ); $higrid_uncompress_html_source = '';//[higrid.net]修改压缩html : 清除换行符,清除制表符,去掉注释标记 foreach ( $chunks as $c ) { if ( strpos( $c, '<pre' ) !== 0 ) { //删除新行和选项卡 $c = preg_replace( '/[\\n\\r\\t]+/', ' ', $c ); // 删除多余的空白 $c = preg_replace( '/\\s{2,}/', ' ', $c ); //删除标记间空白 $c = preg_replace( '/>\\s</', '><', $c ); //删除css&js注释 $c = preg_replace( '/\/\\*.*?\\*\//i', '', $c ); } $higrid_uncompress_html_source .= $c; } return $higrid_uncompress_html_source; }