每個 API 都附 瀏覽器支持率 + 30 秒上手代碼 + 真實業(yè)務場景,復制即用,今晚下班早!
1 Page Visibility API —— 頁面“隱身”探測
支持率: 97%(Chrome 13+、Edge 12+)
場景: 用戶切標簽頁時暫停視頻、停止輪詢
document.addEventListener('visibilitychange', () => { document.visibilityState === 'hidden' ? video.pause() : video.play();});
2 Web Share API —— 一鍵喚起系統(tǒng)分享
支持率: 92%(需 HTTPS)
場景: 把當前文章內(nèi)容分享到微信、微博
if (navigator.share) { navigator.share({ title: '我的新文章', text: '快來看看', url: location.href, });}
3 Broadcast Channel —— 跨標簽頁通信
支持率: 94%(Chrome 54+)
場景: A 標簽頁登錄,B 標簽頁自動刷新
const bc = new BroadcastChannel('login');bc.postMessage({ token: 'abc123' });bc.onmessage = (e) => console.log(e.data);
4 Intl.NumberFormat —— 一鍵千分位
支持率: 100%
場景: 價格、股票、報表格式化
new Intl.NumberFormat('zh-CN').format(1234567); // 1,234,567
5 IntersectionObserver —— 懶加載 + 曝光埋點
支持率: 97%(Chrome 51+)
場景: 圖片懶加載、廣告曝光統(tǒng)計
const io = new IntersectionObserver((entries) => { entries.forEach((e) => e.isIntersecting && loadImg(e.target));});io.observe(img);
6 ResizeObserver —— 元素級尺寸監(jiān)聽
支持率: 94%(Chrome 64+)
場景: 響應式圖表、虛擬滾動
const ro = new ResizeObserver((entries) => { entries.forEach((e) => console.log('尺寸變化', e.contentRect));});ro.observe(chartContainer);
7 Clipboard API —— 無依賴復制
支持率: 95%(需 HTTPS)
場景: 一鍵復制邀請碼、優(yōu)惠券碼
await navigator.clipboard.writeText('COUPON2025');
8 URLSearchParams —— 再也不用正則解析 query
支持率: 100%
場景: 路由、埋點、搜索參數(shù)
const params = new URLSearchParams(location.search);params.get('id'); // ?id=123
9 AbortController —— 可取消的 fetch
支持率: 100%
場景: 取消過期請求、防抖動
const controller = new AbortController();fetch(url, { signal: controller.signal });controller.abort(); // 立即中斷
10 requestIdleCallback —— 主線程垃圾時間調(diào)度器
支持率: 95%(Chrome 47+、Edge 79+)
場景: 埋點、預加載、長計算零阻塞
requestIdleCallback(() => { // 在主線程空閑時執(zhí)行});
一鍵速查表(面試背)
API | 一句話記憶 |
---|---|
Page Visibility | 頁面隱藏時暫停 |
Web Share | 一鍵系統(tǒng)分享 |
Broadcast Channel | 跨標簽頁通信 |
Intl.NumberFormat | 千分位/貨幣格式化 |
IntersectionObserver | 懶加載+曝光 |
ResizeObserver | 元素尺寸監(jiān)聽 |
Clipboard | 無依賴復制 |
URLSearchParams | 解析 query 神器 |
AbortController | 可取消 fetch |
requestIdleCallback | 垃圾時間任務 |
把這張表貼在工位,下次寫功能先翻 3 秒,別再手寫輪詢 + 正則了!