浏览器渲染优--防抖节流懒加载

合理选择css选择器

相比于.content-title-span,使用.content .title span时,浏览器计算样式所要花费的时间更多。使用后面一种规则,浏览器必须遍历页面上所有 span 元素,先过滤掉祖先元素不是.title的,再过滤掉.title的祖先不是.content的。嵌套的层级更多,匹配所要花费的时间代价自然更高。

减少DOM访问

JS 引擎和渲染引擎是两个独立的线程。当我们用 JS 去操作 DOM 时,本质上是 JS 引擎和渲染引擎之间进行了“跨界交流”,交流依赖了桥接接口作为“桥梁
每操作一次 DOM(不管是为了修改还是仅仅为了访问其值),都要过一次桥

<body>
  <div id="container"></div>
</body>

for(var count=0;count<10000;count++){ 
  document.getElementById('container').innerHTML+='<span>我是一个小测试</span>'
} 
// 只获取一次container,并缓存
let container = document.getElementById('container')
for(let count=0;count<10000;count++){ 
  container.innerHTML += '<span>我是一个小测试</span>'
} 
// 只获取一次container
let container = document.getElementById('container')
let content = ''
for(let count=0;count<10000;count++){ 
  // 累计对DOM的修改操作
  content += '<span>我是一个小测试</span>'
} 
// 将累计的修改操作一次性地应用到 DOM
container.innerHTML = content

DocumentFragment

最大的区别是它不是真实 DOM 树的一部分,它的变化不会触发 DOM 树的重新渲染,且不会对性能产生影响。所以性能耗费的比较少
https://developer.mozilla.org/zh-CN/docs/Web/API/DocumentFragment

<ul id="list"></ul>

const list = document.querySelector("#list");
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

fruits.forEach((fruit) => {
  const li = document.createElement("li");
  li.textContent = fruit;
  fragment.appendChild(li);
});

list.appendChild(fragment);

事件委托

将子元素的事件绑定在父元素上 减少对dom的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul class="parent">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
      </ul>
      
    <script>
document.querySelector('.parent').addEventListener('click', (event) => {
  var target = event.target
  if (target.nodeName.toLocaleLowerCase() === 'li') {
    console.log(target.innerHTML + ' clicked');
  }
});

    </script>
</body>
</html>

节流防抖

事件节流 简单来说,就是从一个时间点开始,在某段时间,无论触发了多少次回调,我都只认第一次,并在计时结束时给予响应

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .scrollFont{
        background-color: bisque;
        width: 200px;
        height:500px;
    }
</style>
<body>
    <div class="scrollFont">
        <div>

        </div>
    </div>
    <script>
        function throttle(func, delay) {
            let lastExecTime = 0;
            return function () {
                const currentTime = Date.now();

                if (currentTime - lastExecTime > delay) {
                    func.apply(this, arguments);
                    lastExecTime = currentTime;
                }
            };
        }

        // 示例函数,用于演示滑动节流
        function handleScroll() {
            console.log("Handling scroll event...");
        }

        // 使用节流函数包装 handleScroll 函数,设置触发频率为 200 毫秒
        const throttledScroll = throttle(handleScroll, 200);

        // 监听滚动事件,并使用节流函数处理
        window.addEventListener('scroll', throttledScroll);

    </script>
</body>

</html>

防抖

如果一个函数持续地、频繁地触发,那么只在它结束后过一段时间才开始执行。换句话说,如果你持续触发事件,那么防抖函数将不会执行,只有当你停止触发事件后,它才会在指定的延迟时间后执行。这对于防止例如用户在输入框中连续输入时发送过多的Ajax请求等情况非常有用。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn">
        点击
    </button>
    <script>
        function debounce(func, delay) {
            //接受俩参数 一个是function 一个是延长时间

            let timeoutId;
            return function () {
                const context = this;
                const args = arguments;
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    func.apply(context, args);
                }, delay);
            };
        }
        function myFunction() {
            console.log("Debounced function called!");
        }
        const debouncedFunction = debounce(myFunction, 200);

        // 调用防抖函数
        const btn=document.getElementById('btn')
        btn.onclick=function(){
            console.log('9999');
            debouncedFunction()
        }


    </script>
</body>

</html>

懒加载

定义:资源当用户滑动的时候才会显示 在这之前是不加载的

第一种

在这里插入图片描述
利用用户滚动的距离到视口的窗口大小 开始显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    img{
        height: 300px;
        width: 300px;
        margin-bottom: 50px;
        display: block;
    }
    .showHidden{
        height: 500px;
        width: 200px;
        background-color: antiquewhite;
    }
</style>
<body>
    <div class="showHidden">

    </div>
    <img  data-origin="https://t7.baidu.com/it/u=2604797219,1573897854&fm=193&f=GIF" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img1.baidu.com/it/u=435134468,1942448903&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=889" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img0.baidu.com/it/u=3628503530,464378779&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=800">
    <img  data-origin="https://img2.baidu.com/it/u=855369075,175194576&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="">
    <img  data-origin="https://img2.baidu.com/it/u=2004708195,3393283717&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500" alt="">
    <img  data-origin="https://img1.baidu.com/it/u=1331863463,2594844301&fm=253&fmt=auto?w=1067&h=800" alt="">
    <img  data-origin="https://img1.baidu.com/it/u=1331863463,2594844301&fm=253&fmt=auto?w=1067&h=800" alt="">
    <img  data-origin="https://img0.baidu.com/it/u=2788901948,3907873318&fm=253&fmt=auto?w=500&h=281" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img2.baidu.com/it/u=811993169,635123395&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889" alt="">
    <img  data-origin="https://img0.baidu.com/it/u=924031950,2251460669&fm=253&fmt=auto&app=138&f=JPEG?w=1105&h=500" alt="">

<script>
    const images=document.querySelectorAll('img')
    window.addEventListener('scroll',(e)=>{
        images.forEach((imgshow)=>{
            //判断每张图片的位置是否出现在可视区域a
            const imagesTop=imgshow.getBoundingClientRect().top
            if(imagesTop<window.innerHeight){
                //自定义属性浏览器不会像其他属性一样处理
                const dataOrigin=imgshow.getAttribute('data-origin')
                imgshow.setAttribute('src',dataOrigin)
            }
            console.log('触发滚动');
        })
    })
</script>

</body>

</html>

第二种

利用IntersectionObserver给每个图片添加一个观察者 如果每个实例是isIntersecting为true说明滑动到此处 开始将自定义属性的内容转化为真正的src

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    img{
        height: 300px;
        width: 300px;
        margin-bottom: 50px;
        display: block;
    }
    .showHidden{
        height: 500px;
        width: 200px;
        background-color: antiquewhite;
    }
</style>
<body>
    <div class="showHidden">

    </div>
    <img  data-origin="https://t7.baidu.com/it/u=2604797219,1573897854&fm=193&f=GIF" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img1.baidu.com/it/u=435134468,1942448903&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=889" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img0.baidu.com/it/u=3628503530,464378779&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=800">
    <img  data-origin="https://img2.baidu.com/it/u=855369075,175194576&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="">
    <img  data-origin="https://img2.baidu.com/it/u=2004708195,3393283717&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500" alt="">
    <img  data-origin="https://img1.baidu.com/it/u=1331863463,2594844301&fm=253&fmt=auto?w=1067&h=800" alt="">
    <img  data-origin="https://img1.baidu.com/it/u=1331863463,2594844301&fm=253&fmt=auto?w=1067&h=800" alt="">
    <img  data-origin="https://img0.baidu.com/it/u=2788901948,3907873318&fm=253&fmt=auto?w=500&h=281" alt="">
    <div class="showHidden">

    </div>
    <img  data-origin="https://img2.baidu.com/it/u=811993169,635123395&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889" alt="">
    <img  data-origin="https://img0.baidu.com/it/u=924031950,2251460669&fm=253&fmt=auto&app=138&f=JPEG?w=1105&h=500" alt="">

<script>
    //IntersectionObserver 交叉观察 目标元素和可视化窗口会产生交叉区域
    const images=document.querySelectorAll("img")
    const callBack=(arr)=>{
        console.log(arr);
        //接受一个参数 这个参数是个数组
        arr.forEach((details)=>{
            if(details.isIntersecting){
                const seenImage=details.target
                const dataSrc=seenImage.getAttribute('data-origin')
                seenImage.setAttribute('src',dataSrc)
                obserber.unobserve(seenImage);
            }
        // isIntersecting
        })
    }
    const obserber=new IntersectionObserver(callBack)
    images.forEach((imageShow)=>{
        obserber.observe(imageShow)
        
    })
</script>

</body>

</html>
  • 13
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值