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

合理选择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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/675930.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

拿笔记下来!产品采购制造类合同怎样写比较稳妥?

拿笔记下来&#xff01;产品采购制造类合同怎样写比较稳妥&#xff1f; 近日&#xff0c;几经波折&#xff0c;泰中两国终于完成了潜艇采购谈判&#xff01;你知道吗&#xff1f;产品制造类合同或协议在起草前如果没有充分考虑各种因素&#xff0c;可能会导致一系列问题和不利…

奶茶店、女装店、餐饮店是高危创业方向,原因如下:

关注卢松松&#xff0c;会经常给你分享一些我的经验和观点。 现在的俊男靓女们&#xff0c;心中都有一个执念&#xff1a; (1)想证明自己了&#xff0c;开个奶茶去…… (2)想多赚点钱了&#xff0c;加盟餐饮店去…… (3)工作不顺心了&#xff0c;搞个女装店去…… 但凡抱着…

【scau数据库实验一】mysql_navicat_数据库定义实验、基本命令

实验一开始之前&#xff0c;如果还有不会使用navicat建议花五分钟补课哦~ 补课地址&#xff1a;【scau数据库实验先导】mysql_navicat_数据库新建、navicat的使用-CSDN博客 实验目的&#xff1a; 理解和掌握数据库DDL语言&#xff0c;能够熟练地使用SQL DDL语句创建、修改和删…

mac电脑用谷歌浏览器对安卓手机H5页面进行inspect

1、mac上在谷歌浏览器上输入 chrome://inspect 并打开该页面。 2、连接安卓手机到Mac电脑&#xff1a;使用USB数据线将安卓手机连接到Mac电脑。 3、手机上打开要的h5页面 Webview下面选择要的页面&#xff0c;点击inspect&#xff0c;就能像谷歌浏览器页面打开下面的页面&#…

Vue——初识组件

文章目录 前言页面的构成何为组件编写组件组件嵌套注册 效果展示 前言 在官方文档中&#xff0c;对组件的知识点做了一个很全面的说明。本篇博客主要写一个自己的案例讲解。 vue 官方文档 组件基础 页面的构成 说到组件之前&#xff0c;先大致说明下vue中页面的构成要素。 在…

Claude 3可使用第三方API,实现业务流程自动化

5月31日&#xff0c;著名大模型平台Anthropic宣布&#xff0c;Claude3模型可以使用第三方API和工具。 这也就是说&#xff0c;用户通过文本提问的方式就能让Claude自动执行多种任务&#xff0c;例如&#xff0c;从发票中自动提取姓名、日期、金额等&#xff0c;该功能对于开发…

【问题随记】System policy prevents Wi-Fi scans,解决连接 WIFI 需要权限的问题

问题随记 System policy prevents Wi-Fi scans&#xff0c;每次打开我的开发板连接 wifi 都会出现下面的弹窗&#xff0c;这也阻挡了我的WIFI自动连接&#xff0c;然后就需要连上屏幕&#xff0c;输入 wifi 密码&#xff0c;这样才能进行 VNC、SSH 等一系列的连接。 问题解决 …

『 Linux 』缓冲区(万字)

文章目录 &#x1f9a6; 什么是缓冲区&#x1f9a6; 格式化输入/输出&#x1f9a6; 刷新策略&#x1fab6; 块缓冲(fully buffered)&#x1fab6; 无缓冲(unbuffered)&#x1fab6; 行缓冲(line buffered) &#x1f9a6; 现象解释&#x1f9a6; exit()与_exit()&#x1f9a6; 进…

CPU 使用率过高问题排查

文章目录 CPU 使用率过高问题排查1. CPU使用率过高常见问题2. 压力测试2.1 stress安装参数说明测试示例 2.2 stress-ng安装参数说明测试示例 3. 问题排查3.1 使用 top 命令3.2 使用 ps 命令3.3 使用 perf top3.4 vmstat 命令常用信息内存信息磁盘信息 CPU 使用率过高问题排查 …

Plotting World Map in Python

1. 方法一 pygal Plotting World Map Using Pygal in Python import pygal # create a world map worldmap pygal.maps.world.SupranationalWorld() # set the title of map worldmap.title Continents# adding the continents worldmap.add(Africa, [(africa)]) worl…

【微信小程序】小锦哥小程序工具 v2.3.8.0

# 简介 小锦哥小程序工具是一款可以对微信小程序进行解密或者反编译的工具&#xff0c;通过这款工具&#xff0c;可以对别人已经发布的小程序进行解密或者是反编译&#xff0c;然后查看源代码。对于网络安全人员来说&#xff0c;可以使用该工具进行安全审计&#xff0c;发现其…

四川汇聚荣聚荣科技有限公司评价怎么样?

四川汇聚荣聚荣科技有限公司评价如何?在科技日新月异的今天&#xff0c;四川汇聚荣聚荣科技有限公司作为业界的一员&#xff0c;其表现自然引起了广泛关注。那么&#xff0c;这家公司究竟如何呢?接下来&#xff0c;我们将从四个不同方面对其进行深入剖析。 一、技术实力 四川…

3DGS语义分割之LangSplat

LangSplat是CVPR2024的paper. 实现3DGS的语义分割&#xff08;可文本检索语义&#xff09; github: https://github.com/minghanqin/LangSplat?tabreadme-ov-file 主要思想是在3DGS中加入了CLIP的降维语义特征&#xff0c;可用文本检索目标&#xff0c;实现分割。 配置环境&…

三十四、openlayers官网示例Dynamic clusters解析——动态的聚合图层

官网demo地址&#xff1a; https://openlayers.org/en/latest/examples/clusters-dynamic.html 这篇绘制了多个聚合图层。 先初始化地图 &#xff0c;设置了地图视角的边界extent&#xff0c;限制了地图缩放的范围 initMap() {const raster new TileLayer({source: new XYZ…

导入和使用标准模块

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 在Python中&#xff0c;自带了很多实用的模块&#xff0c;称为标准模块&#xff08;也可以称为标准库&#xff09;&#xff0c;对于标准模块&#xf…

韩顺平0基础学java——第15天

p303-326 重写override 和重载做个对比 注&#xff1a;但子类可以扩大范围&#xff0c;比如父类是protected&#xff0c;子类可以是public 多态 方法或对象具有多种形态&#xff0c;是面向对象的第三大特征&#xff0c;多态是建立在封装和继承基础之上的。 多态的具体体现…

Ubuntu server 24 (Linux) 安装部署smartdns 搭建智能DNS服务器

SmartDNS是推荐本地运行的DNS服务器&#xff0c;SmartDNS接受本地客户端的DNS查询请求&#xff0c;从多个上游DNS服务器获取DNS查询结果&#xff0c;并将访问速度最快的结果返回给客户端&#xff0c;提高网络访问速度和准确性。 支持指定域名IP地址&#xff0c;达到禁止过滤的效…

【YOLOv5/v7改进系列】引入ODConv——即插即用的卷积块

一、导言 提出了一种称为全维度动态卷积(ODConv)的新颖设计&#xff0c;旨在克服当前动态卷积方法的局限性并提升卷积神经网络(CNN)的性能。以下是该论文提出的全维度动态卷积设计的优点和存在的缺点分析&#xff1a; 优点&#xff1a; 增强特征学习能力&#xff1a; ODConv通…

第十五届蓝桥杯物联网试题(省赛)

这个省赛题不算难&#xff0c;中规中矩&#xff0c;记得看清A板B板&#xff0c;还有ADC的获取要配合定时器

如何查看本地sql server数据库的ip地址

程序连线SQL数据库&#xff0c;需要SQL Server实例的名称或网络地址。 1.查询语句 DECLARE ipAddress VARCHAR(100) SELECT ipAddress local_net_address FROM sys.dm_exec_connections WHERE SESSION_ID SPID SELECT ipAddress As [IP Address]SELECT CONNECTIONPROPERTY(…