【问题标题】:how to hide html elements while waiting for all components to be loaded?如何在等待所有组件加载时隐藏 html 元素?
【发布时间】:2022-10-06 02:23:22
【问题描述】:

铬灯塔告诉我:

performance 89(橙色)

Cumulative Layout Shift 0.388(红色警报!)

Avoid large layout shifts

html:

<html>
   ...
   <body class=\"loading\">
   ...some static elements
   </body>
   ...
</html>

CSS:

body.loading * { display : none; }

加载DOM时的js:

document.addEventListener(\'DOMContentLoaded\', (e) => {

    //do many dynamic stuff with the DOM depending on user data (&  register events listeners)

  })

& 最后,当 dom 中的所有内容都准备就绪时,通过window.onload(或者如果该事件来得太快,则在一切准备就绪后进行回调):

document.body.classList.remove(\'loading\')

如果我从 html 灯塔中删除 loading 类,则表示性能 100 非常好。

在看到这个灯塔分析之前,我认为我的布局正在从一个简单的加载(css)动画转变为一个完全就绪的页面,在加载过程中用户没有可见的 dom 变化,所以我现在假设我错了,做错了什么& 遗漏了什么。

我应该如何做到这一点,而不是为了获得最佳加载,同时又不会冒着没有准备好显示的元素的风险?

    标签: javascript html performance optimization lighthouse


    【解决方案1】:

    我一直在等待赏金,但事实证明,尽管我没有在那里做任何更改,但现在灯塔不再为 CLS 标记(相反,我在 html、css 和 js 中添加了一些应该做的代码页面变慢了...??)

    所以答案是(至少在被证明之前):

    在页面加载和 javascript 未准备好时隐藏元素不会对性能产生负面影响。

    这是在页面尚未准备好时拥有超轻微调器的极简代码

    const MyOnLoad = function() {
        
        setTimeout(function(){ // only for the sake of displaying here the spinner 2 and half second obv
                  
                  document.body.classList.remove('loading')
            
            }
            ,2500) 
        
    }
    
    window.onload = MyOnLoad
    .loading {
      margin: 34vmin auto;
      border: 0; 
      border-radius: 50%;
      border-top: 0.89vmin solid red;
      width: 21vmin;
      height: 21vmin;
      animation: spinner 2s linear infinite;
    
     }
    
     @keyframes spinner {
      0%   { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
     }
    
     .loading * {display: none;}
    <html>
     <body class="loading">
     </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多