20个前端开发人员可能不太熟悉的“零依赖”浏览器原生API,摘录于他人博客用于笔记,个人记录,原文链接https://juejin.cn/post/7545294766975615015
以下是这些API的详细总结,包括代码示例:
-
ResizeObserver: 精准监听DOM元素尺寸变化,适用于自适应图表和虚拟滚动。
new ResizeObserver(( [e] ) => chart.resize(e.contentRect.width)).observe(chartDom); -
IntersectionObserver: 检测元素进入/离开视口,实现懒加载和曝光埋点,性能无损耗。
new IntersectionObserver(entrieList => entrieList.forEach(e => e.isIntersecting && loadImg(e.target))).observe(img); -
Page Visibility: 侦测标签页隐藏状态,自动暂停视频或停止轮询,节省移动设备电量。
document.addEventListener('visibilitychange', () => document.hidden ? video.pause() : video.play()); -
Web Share: 唤起系统分享面板,直接分享到微信、微博等,需要HTTPS支持。
navigator.share?.({ title: '好文', url: location.href }); -
Wake Lock: 锁定屏幕常亮,防止屏幕自动熄灭,适用于直播、PPT演示等。
await navigator.wakeLock.request('screen'); -
Broadcast Channel: 同域标签页实时广播消息,同步登录状态,替代
localStorage轮询。const bc = new BroadcastChannel('auth'); bc.onmessage = () => location.reload(); -
PerformanceObserver: 无侵入地采集FCP、LCP、FID等性能指标,进行前端性能监控。
new PerformanceObserver(list => list.getEntries().forEach(sendMetric)).observe({ type: 'largest-contentful-paint', buffered: true }); -
requestIdleCallback: 将埋点、日志等任务放入浏览器空闲时间执行,不阻塞首帧渲染。
requestIdleCallback(() => sendBeacon('/log', data)); -
scheduler.postTask: 原生优先级任务队列,在后台运行低优先级任务,保持主线程流畅。
scheduler.postTask(() => sendBeacon('/log', data), { priority: 'background' }); -
AbortController: 随时取消
fetch请求,避免路由切换时的请求竞争。const ac = new AbortController(); fetch(url, { signal: ac.signal }); ac.abort(); -
ReadableStream: 分段读取响应流,边下载边渲染,防止大文件导致的内存溢出。
const reader = response.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; appendChunk(value); } -
WritableStream: 逐块写入磁盘或网络,用于实时保存草稿、上传大文件。
const writer = stream.writable.getWriter(); await writer.write(chunk); -
Background Fetch: PWA后台静默下载,断网后可恢复,用于课程视频预缓存。
await registration.backgroundFetch.fetch('video', [ '/course.mp4' ]); -
File System Access: 读写本地真实文件,需要用户授权,让Web IDE即开即用。
const [fh] = await showOpenFilePicker(); editor.value = await (await fh.getFile()).text(); -
Clipboard: 异步读写剪贴板,无需第三方库,在HTTPS环境下安全复制。
await navigator.clipboard.writeText('邀请码 9527'); -
URLSearchParams: 解析、修改、构造URL查询字符串。
const p = new URLSearchParams(location.search); p.set('page', 2); history.replaceState({}, '', `?${p}`); -
structuredClone: 深拷贝对象、数组、Map、Date,也能复制循环引用的对象。
const copy = structuredClone(state); -
Intl.NumberFormat: 格式化千分位、货币、百分比,用于国际化。
new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(1234567); // ¥1,234,567.00 -
EyeDropper: 浏览器级别的取色器工具,像素级取色,供设计系统直接调用。
const { sRGBHex } = await new EyeDropper().open(); -
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上可能不兼容。