20个“零依赖”的浏览器原生能力

17 阅读2分钟

20个前端开发人员可能不太熟悉的“零依赖”浏览器原生API,摘录于他人博客用于笔记,个人记录,原文链接https://juejin.cn/post/7545294766975615015

以下是这些API的详细总结,包括代码示例:

  1. ResizeObserver: 精准监听DOM元素尺寸变化,适用于自适应图表和虚拟滚动。

    new ResizeObserver(( [e] ) => chart.resize(e.contentRect.width)).observe(chartDom);
    
  2. IntersectionObserver: 检测元素进入/离开视口,实现懒加载和曝光埋点,性能无损耗。

    new IntersectionObserver(entrieList => entrieList.forEach(e => e.isIntersecting && loadImg(e.target))).observe(img);
    
  3. Page Visibility: 侦测标签页隐藏状态,自动暂停视频或停止轮询,节省移动设备电量。

    document.addEventListener('visibilitychange', () => document.hidden ? video.pause() : video.play());
    
  4. Web Share: 唤起系统分享面板,直接分享到微信、微博等,需要HTTPS支持。

    navigator.share?.({ title: '好文', url: location.href });
    
  5. Wake Lock: 锁定屏幕常亮,防止屏幕自动熄灭,适用于直播、PPT演示等。

    await navigator.wakeLock.request('screen');
    
  6. Broadcast Channel: 同域标签页实时广播消息,同步登录状态,替代localStorage轮询。

    const bc = new BroadcastChannel('auth'); bc.onmessage = () => location.reload();
    
  7. PerformanceObserver: 无侵入地采集FCP、LCP、FID等性能指标,进行前端性能监控。

    new PerformanceObserver(list => list.getEntries().forEach(sendMetric)).observe({ type: 'largest-contentful-paint', buffered: true });
    
  8. requestIdleCallback: 将埋点、日志等任务放入浏览器空闲时间执行,不阻塞首帧渲染。

    requestIdleCallback(() => sendBeacon('/log', data));
    
  9. scheduler.postTask: 原生优先级任务队列,在后台运行低优先级任务,保持主线程流畅。

    scheduler.postTask(() => sendBeacon('/log', data), { priority: 'background' });
    
  10. AbortController: 随时取消fetch请求,避免路由切换时的请求竞争。

    const ac = new AbortController(); fetch(url, { signal: ac.signal }); ac.abort();
    
  11. ReadableStream: 分段读取响应流,边下载边渲染,防止大文件导致的内存溢出。

    const reader = response.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; appendChunk(value); }
    
  12. WritableStream: 逐块写入磁盘或网络,用于实时保存草稿、上传大文件。

    const writer = stream.writable.getWriter(); await writer.write(chunk);
    
  13. Background Fetch: PWA后台静默下载,断网后可恢复,用于课程视频预缓存。

    await registration.backgroundFetch.fetch('video', [ '/course.mp4' ]);
    
  14. File System Access: 读写本地真实文件,需要用户授权,让Web IDE即开即用。

    const [fh] = await showOpenFilePicker(); editor.value = await (await fh.getFile()).text();
    
  15. Clipboard: 异步读写剪贴板,无需第三方库,在HTTPS环境下安全复制。

    await navigator.clipboard.writeText('邀请码 9527');
    
  16. URLSearchParams: 解析、修改、构造URL查询字符串。

    const p = new URLSearchParams(location.search); p.set('page', 2); history.replaceState({}, '', `?${p}`);
    
  17. structuredClone: 深拷贝对象、数组、Map、Date,也能复制循环引用的对象。

    const copy = structuredClone(state);
    
  18. Intl.NumberFormat: 格式化千分位、货币、百分比,用于国际化。

    new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(1234567); // ¥1,234,567.00
    
  19. EyeDropper: 浏览器级别的取色器工具,像素级取色,供设计系统直接调用。

    const { sRGBHex } = await new EyeDropper().open();
    
  20. WebCodecs: 原生硬解码音视频,实现4K 60帧流畅播放,降低CPU占用。

    const decoder = new VideoDecoder({ output: frame => ctx.drawImage(frame, 0, 0), error: console.error }); decoder.configure({ codec: 'vp09.00.10.08' });
    

文章还提到 requestIdleCallback 存在兼容性问题,例如在iOS上可能不兼容。