前端效能優化的關鍵在於減少 HTTP 請求數量。本文實作一組 PHP 函數,自動合併多個 JS/CSS 檔案為單一快取檔案,支援開發/生產環境切換與分組載入。
<?php
define('COMBINE_JS', true);
define('COMBINE_CSS', true);
define('APPLICATION_JS_ROOT', 'E:/wwwroot/m/js/');
define('APPLICATION_CSS_ROOT', 'E:/wwwroot/m/css/');
define('SC_ROOT', 'E:/wwwroot/m/static_cache/'); // 快取實體路徑
define('SC_URL', 'https://www.localhost.com/m/static_cache/'); // 快取公開 URL
define('APPLICATION_JS', 'https://www.localhost.com/m/js/');
define('APPLICATION_CSS', 'https://www.localhost.com/m/css/');
?>
<?php
function load_combine_js($js_files, $path = array(), $force_original = false, $part = 1) {
if (!is_array($js_files)) return false;
// 預設路徑
if (empty($path)) {
$path_url = APPLICATION_JS;
$path_root = APPLICATION_JS_ROOT;
}
// 強制原始載入或關閉合併功能
if ($force_original || !COMBINE_JS) {
$output = '';
foreach ($js_files as $file) {
$output .= "<script src='{$path_url}{$file}.js'></script>\n";
}
echo $output;
return true;
}
// 以腳本名稱 + 分組編號產生快取檔名
$cache_filename = 'js-' . md5($_SERVER['SCRIPT_NAME'] . $part) . '.js';
// 快取不存在時建立
if (!file_exists(SC_ROOT . $cache_filename)) {
$content = '';
foreach ($js_files as $file) {
$full_path = $path_root . $file . '.js';
if (file_exists($full_path)) {
$content .= file_get_contents($full_path) . "\n";
}
}
file_put_contents(SC_ROOT . $cache_filename, $content);
}
echo "<script src='{$cache_filename}'></script>\n";
return true;
}
?>
<?php
function load_combine_css($css_files, $path = array(), $force_original = false, $part = 1) {
if (!is_array($css_files)) return false;
if (empty($path)) {
$path_url = APPLICATION_CSS;
$path_root = APPLICATION_CSS_ROOT;
}
if ($force_original || !COMBINE_CSS) {
$output = '';
foreach ($css_files as $file) {
$output .= "<link href='{$path_url}{$file}.css' rel='stylesheet' type='text/css' />\n";
}
echo $output;
return true;
}
$cache_filename = 'css-' . md5($_SERVER['SCRIPT_NAME'] . $part) . '.css';
if (!file_exists(SC_ROOT . $cache_filename)) {
$content = '';
foreach ($css_files as $file) {
$full_path = $path_root . $file . '.css';
if (file_exists($full_path)) {
$content .= file_get_contents($full_path) . "\n";
}
}
file_put_contents(SC_ROOT . $cache_filename, $content);
}
echo "<link href='{$cache_filename}' rel='stylesheet' type='text/css' />\n";
return true;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>合併載入範例</title>
<?php
// 開發模式:強制載入原始檔案
load_combine_js(array('a', 'b'), array(), true);
load_combine_css(array('1', '2'), array(), true);
// 生產模式:載入合併快取
load_combine_js(array('a', 'b'));
load_combine_css(array('1', '2'));
?>
</head>
<body>內容區塊</body>
</html>
md5_file()),內容變更自動更新檔名,解決瀏覽器快取問題matthiasmullie/minify 套件進行壓縮Cache-Control: max-age=31536000 並啟用 Gzipasync 或 defer 屬性,避免阻塞渲染SC_ROOT 目錄可寫入SC_URL 結構此實作適合中小型專案快速導入前端資源合併,無需引入複雜的建構流程即可獲得顯著效能提升。