DOMContentLoaded 与 load 事件的区别

 

  1. DOMContentLoaded 事件

    • 当文档 DOM 完全加载并解析完成时触发,但不包括样式表、图片、脚本等资源的加载。
    • 此时可以立即访问到页面上的所有元素,并且可以对它们进行操作。
    • 适用于大多数需要在页面加载后立即执行的操作,如绑定事件、修改 DOM 等。
  2. load 事件

    • 当整个页面(包括所有依赖资源,如样式表、图片、脚本等)都加载完毕时触发。
    • 此时页面完全加载完成,所有资源都已经就绪。
    • 适用于需要在页面所有资源加载完成后执行的操作,如图像预加载、统计分析等。


    • -webkit-overflow-scroll: touch;
          transform: translateZ(0);
      复制代码
      // // 使用示例
      // function printScrollbarWidth() {
      //     const scrollbarWidth = getScrollbarWidth();
      //     console.log(`Scrollbar Width: ${scrollbarWidth}px`);
      // }
      
      // // 在页面加载完成后调用
      // document.addEventListener('DOMContentLoaded', () => {
      //     printScrollbarWidth();
      // });
      
      // document.addEventListener('onload', () => {
      //     printScrollbarWidth();
      // });
      复制代码
      复制代码
      function getScrollbarWidth() {
        // 创建一个隐藏的div,设置其宽度、高度、overflow属性来产生滚动条
        const div = document.createElement('div');
        div.style.width = '100px';
        div.style.height = '100px';
        div.style.overflow = 'scroll';
        div.style.position = 'absolute';
        div.style.top = '-9999px'; // 确保div不在视野内
        
        document.body.appendChild(div); // 将div添加到文档中
        const scrollbarWidth = div.offsetWidth - div.clientWidth; // 计算滚动条宽度
        document.body.removeChild(div); // 移除div
        
        return scrollbarWidth;
        
      }
       
      // 使用函数
      const scrollbarWidth = getScrollbarWidth();
      getScrollbarWidth
          console.log(scrollbarWidth);
          document.body.style.paddingRight = `${scrollbarWidth}px`;
      复制代码

       

       

posted @   a瑶池  阅读(19)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示