JS 優化分為「下載體積優化」與「執行效能優化」兩大面向。本文系統整理壓縮工具、撰寫習慣、執行期優化、工具鏈整合,助您交付極速體驗。
| 工具 | 特點 | 適用場景 |
|---|---|---|
| Terser | ES6+ 支援最好、Tree-shaking 整合、Source Map 完整 | 現代專案標準(Webpack/Rollup/Vite 內建) |
| ESBuild | Go 編寫、極速、支援壓縮 | 大型專案、Vite/ESBuild 用戶 |
| SWC | Rust 編寫、極速、支援 TypeScript | Next.js、Deno、大型單體倉庫 |
| UglifyJS (ES5) | 僅支援 ES5、已停止維護 | 舊專案維護 |
// Terser CLI 範例
npx terser input.js -o output.min.js -c -m --module
# -c 壓縮 -m 混淆變數名 --module ES 模組
// 1. 縮短判斷
if (obj != null) → if (obj) // 排除 null/undefined
if (obj === null || obj === undefined) → if (!obj)
// 2. 陣列/物件字面量
var arr = new Array(); → const arr = [];
var obj = new Object(); → const obj = {};
// 3. 箭頭函式隱式回傳
const double = x => x * 2;
// 4. 解構賦值
const { a, b } = props;
const [first, second] = list;
// 5. 模板字面量
const url = `https://api.com/v1/${id}?key=${token}`;
// 動態 import:按需載入
button.addEventListener('click', () => {
import('./heavy-module.js').then(module => {
module.init();
});
});
// 差
for (let i = 0; i < arr.length; i++) { ... }
// 好:快取長度
for (let i = 0, len = arr.length; i < len; i++) { ... }
// 更好:for-of(陣列)或 forEach/map/filter/reduce
for (const item of arr) { ... }
arr.forEach(item => { ... });
// 反向迴圈(需從後往前、或刪除元素時)
for (let i = arr.length - 1; i >= 0; i--) { ... }
現代引擎對 `for-of`、`forEach` 優化極佳,可讀性最高,**優先使用高階函式**。
// 差:每次迴圈觸發重繪
items.forEach(item => {
container.innerHTML += `${item}`;
});
// 好:組裝字串一次寫入
const html = items.map(item => `${item}`).join('');
container.innerHTML = html;
// 最好:DocumentFragment 批次掛載
const frag = document.createDocumentFragment();
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
frag.appendChild(div);
});
container.appendChild(frag);
// 差
function update() {
document.getElementById('box').style.left = x + 'px';
document.getElementById('box').style.top = y + 'px';
}
// 好
const box = document.getElementById('box');
function update() {
box.style.left = x + 'px';
box.style.top = y + 'px';
}
// 差:為每個 li 綁定事件
document.querySelectorAll('#list li').forEach(li => {
li.addEventListener('click', handler);
});
// 好:父層單一監聽
document.getElementById('list').addEventListener('click', e => {
if (e.target.matches('li')) handler(e);
});
// 滾動、觸控事件標記 passive=true,瀏覽器可異步處理,不阻塞主執行緒
window.addEventListener('scroll', onScroll, { passive: true });
element.addEventListener('touchstart', onTouch, { passive: true });
// main.js
const worker = new Worker('compute.worker.js');
worker.postMessage({ data: hugeArray });
worker.onmessage = e => console.log('結果:', e.data);
// compute.worker.js
self.onmessage = e => {
const result = heavyComputation(e.data.data);
self.postMessage(result);
};
優化是持續過程,**先測量、再優化、再驗證**,避免過早優化浪費開發資源。