提升页面访问速度的优化方法有很多,其中包括对 HTML 代码的压缩,将HTML代码格式化为单行,去除回车注释等无效字符串以增加网页传速效率. Nginx , Apache 也有类似的模块可以直接输出类似的单行HTML代码。
Typecho也有类似的插件,如「CompressHTML-For-Typecho」->传送门,但存在一些兼容问题,这里提供一个修改的版本,将代码压缩功能集成到Typecho中。
(实测与HandSome主题兼容,与TpCache插件兼容)。
下面是教程,比较简单~
添加函数
还是那段压缩代码函数function compressHtml($html_source) {
$chunks = preg_split('/(.*?|.*?|||)/msi', $html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
$compress = '';
foreach ($chunks as $c) {
if (strtolower(substr($c, 0, 19)) == '') {
$c = substr($c, 19, strlen($c) - 19 - 20);
$compress .= $c;
continue;
} else if (strtolower(substr($c, 0, 12)) == '') {
$c = substr($c, 12, strlen($c) - 12 - 13);
$compress .= $c;
continue;
} else if (strtolower(substr($c, 0, 4)) == '
$compress .= $c;
continue;
} else if (strtolower(substr($c, 0, 7)) == '
$c = '';
foreach ($tmps as $tmp) {
if (strpos($tmp, '//') !== false) {
if (substr(trim($tmp), 0, 2) == '//') {
continue;
}
$chars = preg_split('//', $tmp, -1, PREG_SPLIT_NO_EMPTY);
$is_quot = $is_apos = false;
foreach ($chars as $key => $char) {
if ($char == '"' && $chars[$key - 1] != '\\' && !$is_apos) {
$is_quot = !$is_quot;
} else if ($char == '\'' && $chars[$key - 1] != '\\' && !$is_quot) {
$is_apos = !$is_apos;
} else if ($char == '/' && $chars[$key + 1] == '/' && !$is_quot && !$is_apos) {
$tmp = substr($tmp, 0, $key);
break;
}
}
}
$c .= $tmp;
}
}
$c = preg_replace('/[\\n\\r\\t]+/', ' ', $c);
$c = preg_replace('/\\s{2,}/', ' ', $c);
$c = preg_replace('/>\\s', '> <', $c);
$c = preg_replace('/\\/\\*.*?\\*\\//i', '', $c);
$c = preg_replace('//', '', $c);
$compress .= $c;
}
return $compress;
}
将其放到HandSome主题的function.php的末尾
添加启用
然后打开footer.php,在末尾加上下面代码<?php $html_source = ob_get_contents(); ob_clean(); print compressHtml($html_source); ob_end_flush(); ?>
保存好这两个文件,然后覆盖原文件
兼容其他代码
当然代码压缩可能会与一些插件不兼容,可以使用下面方法自行修改插件代码来保证这些不兼容的代码可以运行
不兼容代码
不兼容代码
更新:
Q:handsome主题 v6.0.0 版本开始,function.php文件被加密了,无法添加函数怎么办?
A:handsome主题 libs 目录下随便找个文件放入 compressHTML 函数后可在主题文件调用;handsome主题 v7.0 新增了functions_mine.php 文件任何需要修改或增加新函数的操作都可以在此文件进行。