打包後的 JavaScript 越大,下載、解析、執行都越慢,在中低階手機上尤其明顯。其中很大一部分是「這一頁根本不會用到」的程式碼。
靜態與動態 import
// 靜態:一定會被打包進主檔案
import { Chart } from 'chart.js/auto';
// 動態:需要時才下載,回傳 Promise
const { Chart } = await import('chart.js/auto');
打包工具(Vite、webpack、Rollup)看到動態 import(),會自動把它拆成獨立的檔案。
使用者操作時才載入
document.querySelector('#show-report').addEventListener('click', async () => {
const { renderReport } = await import('./report.js');
renderReport(document.querySelector('#report'));
});
進入畫面時才載入
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
const { initMap } = await import('./map.js');
initMap(entry.target);
}, { rootMargin: '200px' });
observer.observe(document.querySelector('#map'));
rootMargin: '200px' 讓元素還沒進入畫面前就開始下載,使用者捲到時通常已經準備好。
React 的寫法
import { lazy, Suspense } from 'react';
const Editor = lazy(() => import('./Editor'));
export function Page() {
return (
<Suspense fallback={<p>載入編輯器…</p>}>
<Editor />
</Suspense>
);
}
預先載入
確定使用者很快會用到時,可以提早下載但不執行:
<link rel="modulepreload" href="/assets/report-abc123.js">
WARNING
不要把所有東西都拆開。每個分割出來的檔案都是一次額外請求,太碎反而變慢。優先處理體積大、使用率低的模組。
找出值得拆的模組
npx vite-bundle-visualizer
看看哪些套件佔了最大面積,再判斷它們是不是每一頁都需要。
發表留言