ThinkPHP项目HTML压缩与优化

wen PHP项目 4

本文目录导读:

ThinkPHP项目HTML压缩与优化

  1. 输出缓冲压缩
  2. ThinkPHP配置优化
  3. 模板优化
  4. 使用中间件进行压缩
  5. 使用第三方压缩库
  6. .htaccess或Nginx配置优化
  7. 完整优化示例
  8. 注意事项

在ThinkPHP项目中进行HTML压缩与优化,可以从以下几个方面入手:

输出缓冲压缩

在入口文件(index.php)添加压缩代码

// index.php
<?php
// 定义应用目录
define('APP_PATH', __DIR__ . '/../application/');
// 加载框架引导文件
require __DIR__ . '/../thinkphp/start.php';
// 添加输出压缩
ob_start('html_compress');
function html_compress($content) {
    $search = [
        '/\>[^\S ]+/s',     // 去掉标签后面的空白
        '/[^\S ]+\</s',     // 去掉标签前面的空白
        '/(\s)+/s',         // 将多个空白换成一个空格
        '/<!--(.|\s)*?-->/', // 去掉HTML注释
        '/\n/s',            // 去掉换行符
    ];
    $replace = [
        '>',
        '<',
        '\\1',
        '',
        '',
    ];
    $content = preg_replace($search, $replace, $content);
    return $content;
}
// 注册保存函数
register_shutdown_function('ob_end_flush');

ThinkPHP配置优化

在config.php中添加配置

// application/config.php
return [
    // 开启模板压缩
    'tpl_cache' => true,
    // 模板代码压缩
    'tpl_parse_str' => [
        'strip_space' => true,  // 去除空格
        'strip_comment' => true, // 去除注释
        'strip_blank' => true,  // 去除空行
    ],
    // 页面压缩
    'output_compress' => true,
    // 设置输出压缩级别
    'output_compress_level' => 6,
];

模板优化

使用布局模板(Template Layout)

// application/config.php
'layout_on' => true,
'layout_name' => 'layout',
// 创建布局文件
// application/view/layout.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">{$title}</title>
    {__CSS__}
    {__JS__}
</head>
<body>
    {__CONTENT__}
</body>
</html>

静态资源优化

// 在模板中使用CDN或压缩后的资源
<link rel="stylesheet" href="https://cdn.example.com/css/style.min.css">
<script src="https://cdn.example.com/js/script.min.js"></script>
// 使用版本号控制缓存
<link rel="stylesheet" href="__STATIC__/css/style.css?v={$version}">

使用中间件进行压缩

// application/http/middleware/Compress.php
namespace app\http\middleware;
class Compress
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        if (is_object($response) && method_exists($response, 'content')) {
            $content = $response->getContent();
            // 压缩HTML
            $content = $this->compressHtml($content);
            $response->content($content);
        }
        return $response;
    }
    private function compressHtml($content)
    {
        $search = [
            '/\>[^\S ]+/s',
            '/[^\S ]+\</s',
            '/(\s)+/s',
            '/<!--(.|\s)*?-->/',
        ];
        $replace = ['>', '<', '\\1', ''];
        return preg_replace($search, $replace, $content);
    }
}
// 注册中间件
// application/middleware.php
return [
    'app\http\middleware\Compress',
];

使用第三方压缩库

composer安装html压缩库

composer require wyrihaximus/html-compress
// 在控制器中使用
use WyriHaximus\HtmlCompress\Factory;
class Index
{
    public function index()
    {
        // 获取输出内容
        $html = $this->fetch('index');
        // 压缩HTML
        $compressor = Factory::construct();
        $compressed = $compressor->compress($html);
        return $compressed;
    }
}

.htaccess或Nginx配置优化

Apache (.htaccess)

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>

Nginx

# 开启gzip压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

完整优化示例

// 在基类控制器中添加压缩方法
class BaseController extends Controller
{
    protected function compressOutput($content)
    {
        // 移除HTML注释
        $content = preg_replace('/<!--(.*)-->/Uis', '', $content);
        // 压缩连续空白
        $content = preg_replace('/\s+/', ' ', $content);
        // 删除换行符
        $content = preg_replace('/>\s+</', '><', $content);
        // 压缩CSS和JS片段
        $content = preg_replace_callback('/<style[^>]*>(.*?)<\/style>/is', function($matches) {
            return '<style>' . preg_replace('/\s+/', ' ', $matches[1]) . '</style>';
        }, $content);
        $content = preg_replace_callback('/<script[^>]*>(.*?)<\/script>/is', function($matches) {
            return '<script>' . preg_replace('/\s+/', ' ', $matches[1]) . '</script>';
        }, $content);
        return $content;
    }
    // 在继承的控制器中调用
    protected function fetch($template = '', $vars = [], $config = [])
    {
        $content = parent::fetch($template, $vars, $config);
        return $this->compressOutput($content);
    }
}

注意事项

  1. 不要过度压缩:压缩会牺牲一定的可读性,建议保留必要的换行和空格
  2. 排除特定区域:可以使用条件注释或特殊注释标记来排除不需要压缩的区域
  3. 性能权衡:考虑压缩带来的CPU开销与带宽节省之间的平衡
  4. 测试兼容性:压缩后要确保所有浏览器正常渲染

优化效果可以降低页面体积,提高加载速度,建议根据项目实际情况选择合适的压缩策略。

抱歉,评论功能暂时关闭!