我的 js 滑块导致 CLS 分数较低:如何更改滑块的加载方式? [英] My js slider is causing a low CLS score: How to change the way my slider loads?

查看:62
本文介绍了我的 js 滑块导致 CLS 分数较低:如何更改滑块的加载方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌页面速度测试中的 CLS(布局转换)分数很低,我发现这是因为我的滑块加载方式.当页面加载时(主要是在慢速连接上),滑块的图像都在彼此下方加载,当页面加载完成并且 javascript 加载时,只有这样其余的图像才会隐藏并开始滑动.

I'm getting a low CLS (layout shift) score on google page speed test, and I figured out it is because of how my slider loads. When the page is loading (mostly on slow connections) the slider's images are all loaded below eachother, when the page is done loading and the javascript loads, only then are the rest of the images hidden and starts to slide.

我根据教程创建了以下滑块.我不知道如何解决这个问题.我认为最好的方法是尝试隐藏所有其他图像(第一个除外),直到加载 javascript.有没有办法用javascript来实现这一点?或者有更好的解决方案

I created the following slider from a tutorial. I have no idea how to solve this problem. I would think the best way would be to try and hide all the other images (except the first one) until the javascript is loaded. Is there a way to achieve this with javascript? Or is there a better solution

解决这个问题的最佳方法是什么?这是我的滑块代码:

What would be the best way to approach this problem? Here is my slider's code:

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("single-slide");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";
  setTimeout(showSlides, 6000); 
} 

推荐答案

您必须将 display: none 作为默认设置在您的块上,例如使用 css 类.如果您的 javascript 位于页面的末尾(应该是),则浏览器会在您将 display: none 来自 javascript

you have to put the display: none as default on your blocks, using for example css classes. If your javascript is at the end of the page (as it should be) the browser starts to load images before you put the display: none from javascript

这篇关于我的 js 滑块导致 CLS 分数较低:如何更改滑块的加载方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆