Firefox 新标签页扩展性能技巧:加载时间低于100毫秒
发布: (2026年5月4日 GMT+8 08:02)
3 分钟阅读
原文: Dev.to
Source: Dev.to
基准:是什么让新标签页感觉快速?
新标签页会替代 Firefox 内置的页面,而内置页面基本是瞬间加载。如果你的页面超过 200 ms,用户会注意到。目标是:
- 首次绘制(First paint):
:root { --bg: #fff; --text: #1a1a1a; }
body { margin: 0; background: var(--bg); color: var(--text);
font-family: system-ui; }
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
/* Only above‑the‑fold styles here */
为脚本使用 defer
<script src="your-script.js" defer></script>
使用 defer 时,HTML 会在 JavaScript 运行之前渲染,这样用户能够立刻看到内容。
在 DOM 之前应用主题
错误主题的闪烁会让人不适:
<script>
// Runs immediately, before any rendering
(function () {
const theme = localStorage.getItem('theme') || 'auto';
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const effective = theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme;
document.documentElement.setAttribute('data-theme', effective);
})();
</script>
是的,这只是一个很小的同步脚本——但它可以防止 FOUC(无样式内容闪烁)。
首先加载缓存数据
不要等 API 调用完成后才渲染:
async function init() {
// 1. Apply settings from sync storage (fast, local)
const prefs = await browser.storage.sync.get(DEFAULTS);
applyPreferences(prefs);
// 2. Show cached weather immediately (no network needed)
const { weatherCache } = await browser.storage.local.get('weatherCache');
if (weatherCache) {
displayWeather(weatherCache.data);
} else {
showWeatherSkeleton();
}
// 3. Fetch fresh data in background
fetchWeatherAndUpdate(prefs.location);
// 4. Render clocks (pure JS, no async needed)
initClocks(prefs.worldClocks);
}
最小化存储读取次数
将存储读取合并为一次调用:
// BAD: multiple awaits, multiple IPC calls
const { theme } = await browser.storage.sync.get('theme');
const { location } = await browser.storage.sync.get('location');
const { clocks } = await browser.storage.sync.get('clocks');
// GOOD: one IPC call
const { theme, location, clocks } = await browser.storage.sync.get([
'theme',
'location',
'clocks',
]);
性能测量
// Measure your init time
const t0 = performance.now();
await init();
const t1 = performance.now();
console.log(`Init took ${t1 - t0}ms`);
使用 Firefox 内置的 Performance Profiler(F12 → Performance 选项卡)来定位瓶颈。
结果
使用这些技巧,Weather & Clock Dashboard 达到:
- 首次绘制(First paint): ~20 ms(同步应用缓存主题)
- 缓存天气显示(Cached weather displayed): ~40 ms
- 时钟渲染(Clock rendered): ~45 ms
- 新天气可见(Fresh weather visible): ~400 ms(网络条件允许时)
Weather & Clock Dashboard — 免费的 Firefox 新标签页,提供天气、世界时钟和搜索功能。采用 MIT 许可证。