ES新特性和浏览器的 5 种 Observer

ES新特性

  1. String.prototype.replaceAll():使用该方法可以替换字符串中出现的所有子串。
javascript 复制代码
const str = 'Hello, World!';
const replacedStr = str.replaceAll('o', '0');
console.log(replacedStr); // Hell0, W0rld!
  1. Array.prototype.groupBy():该提案引入了一种新方法,允许根据提供的函数对数组元素进行分组。
javascript 复制代码
const numbers = [1, 2, 3, 4, 5, 6];
const grouped = numbers.groupBy((num) => num % 2 === 0 ? 'even' : 'odd');
console.log(grouped);
// Output: { odd: [1, 3, 5], even: [2, 4, 6] }
  1. String.prototype.sliceSet():该功能旨在增强现有的 slice() 方法,允许使用切片语法替换字符串中的子串。
javascript 复制代码
let str = 'Hello, World!';
str.sliceSet(7, 12, 'Earth');
console.log(str); // Hello, Earth!

浏览器的 5 种 Observer Api

网页开发中我们经常要处理用户交互,我们会用 addEventListener 添加事件监听器来监听各种用户操作,比如 click、mousedown、mousemove、input 等,这些都是由用户直接触发的事件。

那么对于一些不是由用户直接触发的事件呢? 比如元素从不可见到可见、元素大小的改变、元素的属性和子节点的修改等,这类事件如何监听呢?

浏览器提供了 5 种 Observer 来监听这些变动:MutationObserver、IntersectionObserver、PerformanceObserver、ResizeObserver、ReportingObserver。

  1. IntersectionObserver 可以监听一个元素和可视区域相交部分的比例,然后在可视比例达到某个阈值的时候触发回调
javascript 复制代码
const intersectionObserver = new IntersectionObserver(  
    function (entries) {      
        console.log('info:');     
        entries.forEach(item => {   
            console.log(item.target, item.intersectionRatio)       
        })   
     }, { threshold: [0.5, 1]}
 );
    intersectionObserver.observe( document.querySelector('#box1'));
    intersectionObserver.observe( document.querySelector('#box2'));

2.MutationObserver 可以监听对元素的属性的修改、对它的子节点的增删改。

javascript 复制代码
const mutationObserver = new MutationObserver((mutationsList) => { 
   console.log(mutationsList)}
 );
 mutationObserver.observe(box, { attributes: true, childList: true });

setTimeout(() => {  
  box.style.background = 'red'
 },2000);
 setTimeout(() => { 
    const dom = document.createElement('button'); 
    dom.textContent = '东东东';   
    box.appendChild(dom);
  },3000);
 setTimeout(() => {  
     document.querySelectorAll('button')[0].remove();
 },5000);

第一次改变的是 attributes,属性是 style:

第二次改变的是 childList,添加了一个节点:

第三次也是改变的 childList,删除了一个节点:

  1. 窗口我们可以用 addEventListener 监听 resize 事件,那元素呢?元素可以用 ResizeObserver 监听大小的改变,当 width、height 被修改时会触发回调。
javascript 复制代码
const box = document.querySelector('#box');

setTimeout(() => {
    box.style.width = '200px';
}, 3000);
const resizeObserver = new ResizeObserver(entries => {
    console.log('当前大小', entries)
});
resizeObserver.observe(box);
  1. PerformanceObserver 用于监听记录 performance 数据的行为,一旦记录了就会触发回调,这样我们就可以在回调里把这些数据上报

  2. ReportingObserver:监听过时的 api、浏览器的一些干预行为的报告,可以让我们更全面的了解网页 app 的运行情况

这些 api 相比 addEventListener 添加的交互事件来说用的比较少,但是在特定场景下都是很有用的。

相关推荐
sbjdhjd3 小时前
Redis 主从复制、哨兵高可用与 Cluster 集群部署实验手册
运维·前端·redis·云原生·开源·bootstrap·html
乐兮创想 小林4 小时前
企业官网移动端性能优化实战:从 Core Web Vitals 到图片/CDN/响应式的工程清单
前端·性能优化·网站建设·北京网站建设公司
疯狂SQL4 小时前
JWT 在线解码、验签、生成一篇讲透:附前端实现、工具架构与在线体验地址
javascript·jwt·编解码·jwt测试
前端一小卒4 小时前
不手写代码的第 30 天,我才明白前端这个岗位还剩什么
前端·javascript·ai编程
Ajie'Blog4 小时前
Copilot Agent Tasks API 开放:AI 编程开始进入后台任务时代
服务器·前端·javascript·人工智能·copilot·ai编程
老毛肚5 小时前
jeecgboot vue TS & 模板化 04
前端·javascript·vue.js
晓13135 小时前
【Cocos Creator 2.x】篇——第二章 入门
javascript·游戏引擎
AI_零食6 小时前
鸿蒙PC Electron跨平台应用开发:24时区时间表应用详解
前端·华为·electron·开源·harmonyos·鸿蒙
Electrolux7 小时前
[onlyoffice-v9]纯前端怎么实现编辑预览office
前端·javascript·github
VidDown7 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman