
1 .资源观察器ResizeObserver是一个浏览车原生的JavaScript API用于监听DOM元素尺寸变化。 其相似于MutationObserver但专门用于考察元素的大小(孙高)变化而无需依赖window.resize事件(后者只对视口变化有敌)。基本用法12345678910111213141516constresizeObserver newResizeObserver(entries {for(letentry of entries) {const{ width, height } entry.contentRect;console.log(元素尺寸${width} x ${height});// entry.target 是被观察的 DOM 元素console.log(目标元素:, entry.target);}});// 开始观察某个元素resizeObserver.observe(document.querySelector(#my-element));// 可选观察多个元素// resizeObserver.observe(element1);// resizeObserver.observe(element2);entry.content rect vs getboundingclientrect ( )entry.contentRect:显示内容区域(不包括paddingbordermargin )类似于getComputedStyle().width/height的计算结果。如果你需要总括border和padding的尺寸可以结合entry.target.getBoundingClientRect()使用。停止视察12345// 停止观察某个元素resizeObserver.unobserve(element);// 停止观察所有元素并释放资源resizeObserver.disconnect();建议:在组件销售(如React的useEffect清理函数Vue的onBeforeUnmount)时调用disconnect()避免内存泄漏。使用场景响式组件:本容器尺寸变化时动态调整子元素(如图表、Canvas、视频)。自定义搏动条或布局:收听内容区域变化以上更新UI。代替费window.onresize:更精确地响应特定元素的尺寸变化而非整个开口。封装组件/封装组件:内部自动配父容器大小。浏览器兼容性✅ Chrome 64✅ Firefox 69✅ Safari 13.1✅ Edge 79ie不支持(需求polyfill )兼容性已非常广泛现代项目可放心使用。️ Polyfill (如需支持旧浏览车)通过GitHub - juggle/resize-observer提供的polyfill :1npm install juggle/resize-observer123456import ResizeObserverfromjuggle/resize-observer;// 如果原生不支持则使用 polyfillif(!window.ResizeObserver) {window.ResizeObserver ResizeObserver;}示例:在React期间使用1234567891011121314151617181920212223import { useEffect, useRef }fromreact;function MyComponent() {constcontainerRef useRef(null);useEffect(() {constobserver newResizeObserver(entries {for(letentry of entries) {console.log(新宽度:, entry.contentRect.width);}});if(containerRef.current) {observer.observe(containerRef.current);}return() {observer.disconnect();// 清理};}, []);returndivref{containerRef}可变尺寸容器/div;}2 .交互观察器IntersectionObserver是一个强大的浏览车原生API用于异闻监听目标元素与祖先元素(或视口)的交叉(相)状态变化。 它常用于实现懒加载、无限滘动、曝光统计、视频触发等场景性能远优于传统scroll事件监视。基本用法1234567891011121314151617181920constobserver newIntersectionObserver((entries, observer) {entries.forEach(entry {// entry.target被观察的 DOM 元素// entry.isIntersecting是否与根viewport 或 root相交// entry.intersectionRatio相交区域占目标元素的比例0 ~ 1// entry.intersectionRect相交区域的矩形信息// entry.boundingClientRect目标元素相对于视口的位置// entry.rootBounds根元素的边界通常是视口if(entry.isIntersecting) {console.log(元素进入视口:, entry.target);// 例如加载图片、触发动画}else{console.log(元素离开视口);}});});// 开始观察某个元素observer.observe(document.querySelector(#my-element));配置选项(可选)1234567constoptions {root:null,// 默认为视口viewport可设为某个祖先元素rootMargin:0px,// 类似 CSS margin扩展或收缩根的边界支持负值threshold: 0.5// 触发回调的相交比例阈值0 ~ 1可为数字或数组};constobserver newIntersectionObserver(callback, options);threshold示例:threshold: 0:只要有一点进入就触发(默认)。threshold: 1:完全进入才触发。threshold: [0, 0.25, 0.5, 0.75, 1]:在0%、25%、50% ...时都触发。停止视察12observer.unobserve(element);// 停止单个元素observer.disconnect();// 停止所有并释放资源建议:在组装时调用disconnect()防止内存泄漏。典型的应用场合1 .图片添加12345678910111213constimgObserver newIntersectionObserver((entries) {entries.forEach(entry {if(entry.isIntersecting) {constimg entry.target;img.src img.dataset.src;// 从>2.滘动到底部自动加载(无限滘动)观察一个“哨兵”元素(如分页加载提示)该元素进入视口时触发加载。3.曝光埋点/广告可见性统计在本广告或内容区域进入视口一定比例时报告“曝光”事件。4.滘动动画(如AOS败果)元素进入视口时添加的CSS视频类。浏览器兼容性✅ Chrome 51✅ Firefox 55✅ Safari 12.1✅ Edge 15ie不支持(需求polyfill )现代手机支持良好移动端也广泛可用。️ Polyfill (兼容旧浏览车)官方推荐polyfill (由W3C团队维护) :1npm install intersection-observer12// 在应用入口引入自动填充 window.IntersectionObserverimportintersection-observer;注意: polyfill会回退scrollgetBoundingClientRect()性能差仅用于兼容。与ResizeObserver/MutationObserver对比三者互补常结合使用。小技巧使用rootMargin: 100px可以以上前言触发(在元素距离视口也有100px时就加载)。在img loadinglazy普及性的今天简单图片添加可直接使用的HTML属性但无法维持需求IntersectionObserver。3 .页可视化Page Visibility API是一个浏览器原生API用于测量当前网页是否正确用户可见(立即是否在前台标签页或被最小化/切换到后台)。 它可以帮助开发者优化性能、节省资源、或实现特定业务编辑(如暂停视频、停止咨询、统计停留时长等)。核心属性与事件1.document.visibilityState回复当前页面的可见性状态可能侧包括:实际开发中主要关注visible和hidden。2.document.hidden(已弃建议用visibilityStatetrue:不可见页面false:看得见页面仍然可用但MDN建议使用visibilityState。3.visibilitychange事件当页面可见性状态改变时触发。基本用法示例123456789101112function handleVisibilityChange() {if(document.visibilityState visible) {console.log(页面回到前台);// 恢复视频播放、重启定时器、刷新数据等}elseif(document.visibilityState hidden) {console.log(页面进入后台);// 暂停视频、停止轮询、保存状态等}}// 监听可见性变化document.addEventListener(visibilitychange, handleVisibilityChange);典型的应用场合1 .暂停/恢复媒体播放123456789constvideo document.querySelector(video);document.addEventListener(visibilitychange, () {if(document.hidden) {video.pause();}else{video.play();}});2 .停止不必要的轮训或定时任务12345678910111213141516171819letintervalId;function startPolling() {intervalId setInterval(fetchData, 5000);}function stopPolling() {clearInterval(intervalId);}document.addEventListener(visibilitychange, () {if(document.hidden) {stopPolling();}else{startPolling();}});startPolling();// 初始启动3 .用户停留时间统计12345678910111213141516letstartTime Date.now();lettotalVisibleTime 0;document.addEventListener(visibilitychange, () {if(document.hidden) {totalVisibleTime Date.now() - startTime;}else{startTime Date.now();}});// 页面卸载时上报总可见时长window.addEventListener(beforeunload, () {totalVisibleTime Date.now() - startTime;sendToAnalytics({ visibleTime: totalVisibleTime });});4.节省资源(如Canvas视频、WebGL )页面不可见时暂时停止污染循环减少CPU/GPU消耗。浏览器兼容性✅ Chrome 13✅ Firefox 10✅ Safari 7✅ Edge 12IOs safari/Android浏览器(现代版本)兼容性极好几乎所有现代浏览车都支持。注意事项不保证准确性:在某些系统(如macOS快速切换)中状态可切换有微小延迟。是非用户活跃度测量:页面可见≠用户正在查看(用户可以切到其他应用但浏览器开口仍在前台)。与blur/focus事件上的区别window.onfocus/window.onblur:监听孔径焦点(如切换至其他应用)。visibilitychange:监听见分晓(即使开口有焦点但在后台也算hidden )。双方可结合使用以上获得更全面的状态判断。拓展:结合focus/blur更精确的判断1234567891011121314151617letisPageVisible !document.hidden;letisWindowFocused !document.hasFocus();window.addEventListener(focus, () {isWindowFocused true;if(isPageVisible) {console.log(用户很可能正在看页面);}});window.addEventListener(blur, () {isWindowFocused false;});document.addEventListener(visibilitychange, () {isPageVisible !document.hidden;});4.Web Share APIWeb Share API是一个现代浏览器提供的原生API允许网页调用操作系统级别的共享功能用户将内容(如链接、文本、标题等)快速共享到设备上安装的其他应用(如微信、邮件、短信、笔记等)。基本用法1234567891011121314151617181920if(navigator.share) {navigator.share({title:分享标题,text:分享的描述文字,url:https://example.com}).then(() {console.log(分享成功);}).catch((error) {if(error.name AbortError) {console.log(用户取消了分享);}else{console.error(分享失败:, error);}});}else{// 回退方案显示自定义分享按钮或提示alert(您的浏览器不支持 Web Share API请手动复制链接);}⚠️必须在用户手势触发的上下文中调用(如点滴事件)否决会抛出安全错误。安全授予限制仅安全上下文:必须在HTTPS(或localhost)以下使用。用户手势要求:只能在click、touchend等用户操作调谐。字段非全部必需:但至少要提供title、text、url中一个(推荐提供url。无法控制目标应用:分享目标由操作系统决定开发者无法指定(如“只是分享到微信”)。支持情况(截至2025年)