傳統 SSI <!--#include virtual="header.shtml"--> 會導致每頁請求都重複下載公共片段(頁首、側欄、頁尾、公共 JS),浪費頻寬與延遲渲染。本文提出「SSI 條件判斷 + Cookie 狀態同步 + localStorage 實體快取」三位一體方案,實現公共片段瀏覽器端快取。
html_aside=01)。include 輸出原始 HTML,同時輸出 JS 將片段寫入 localStorage 並設定 Cookie 版本號。localStorage 讀取並 innerHTML 渲染至佔位容器。<!--#if expr="${HTTP_COOKIE} = /(;)?html_aside=01(;)?/" -->
<script>localData.loadFromCache('aside');</script>
<!--#else -->
<!--#include virtual="shtmlCache/aside.shtml" -->
<script>localData.saveToCache('aside');</script>
<!--#endif -->
var localData = {
saveToCache: function(key) {
var html = document.getElementById(key).innerHTML;
localStorage.setItem(key, html);
document.cookie = key + "=01; path=/; max-age=2592000"; // 30 天
},
loadFromCache: function(key) {
var html = localStorage.getItem(key);
if (html) document.getElementById(key).innerHTML = html;
}
};
01→02),強制所有用戶重新快取。localStorage 可被 JS 竄改,若站點存在 XSS 漏洞,攻擊者可植入惡意 HTML。max-age)。此方案在不變更後端架構前提下,以極低成本實現「邊緣快取」效果。