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 添加的交互事件来说用的比较少,但是在特定场景下都是很有用的。

相关推荐
mCell1 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 小时前
Node.js 子进程:child_process
前端·javascript
excel4 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel5 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼7 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping7 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙8 小时前
[译] Composition in CSS
前端·css
白水清风8 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix8 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278008 小时前
new、原型和原型链浅析
前端·javascript