如何提高网站速度得分?

时间:2017-11-10 18:53:00

标签: javascript html css image performance

我开发了一个纯粹的" HTML,CSS,JS"仅包含文本和图像的网站,虽然它需要花费很多时间来加载特殊图像(所有5页图像的大小为16MB),但有些图像(每页的主要图像)大约是&#34 ; 3000px x高度" ,那是因为它具有响应性,我想要覆盖大部分屏幕尺寸,宽度和高度都会根据屏幕尺寸而变化,我尝试了google speed insights但它没有帮助& #34; https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.zhtml.aba.ae"

我也试过了gtmetrix" https://gtmetrix.com/reports/www.zhtml.aba.ae/LzvOPr5R"

但它只能减少少量的图像尺寸。

如何提高我的网站速度特别是图片?

1 个答案:

答案 0 :(得分:0)

// 1. Convert node list of all images with 
// data-src attribute to an array
const imgs = [ ...document.querySelectorAll('img[data-src]') ];
// 2. Wrap the code on a feature test for IntersectionObserver
if ('IntersectionObserver' in window) {
  // 3. Create the IntersectionObserver and bind it to the function 
  // we want it to work with
  let observer = new IntersectionObserver(onChange);

  function onChange(changes) {
    // 4. For each image that we want to change
    changes.forEach((change) => {
      // * take image url from `data-src` attribute
      change.target.src = change.target.dataset.src;
      // * Stop observing the current target
      observer.unobserve(change.target);
    })
  }

// 5. Observe each image derived from the array above
  imgs.forEach((img) => observer.observe(img));
} else {
// 6. if the browser doesn't support Intersection Observer 
// we log to console and load images manually
  console.log('Intersection Observers not supported');
  function loadImages(imgs) {
    imgs.forEach((image) => {
      image.src = image.dataset.src;
    })
  }
  loadImages(imgs);
}
.img-atr{
  width: 400px;
}
<img class="img-atr" data-src='https://cdn2.droom.in/photos/images/drm/super-cars.png'  />
<br><br><br>
<img class="img-atr" data-src='https://static.pexels.com/photos/50704/car-race-ferrari-racing-car-pirelli-50704.jpeg'  />
<br><br><br>
<img class="img-atr" data-src='https://i.autotrader.co.za/merlin-image-server/web-content/cars-for-sale-south-africa.jpg'  />
<br><br><br>
<img class="img-atr" data-src='http://bestride.com/wp-content/uploads/2015/11/Used-Car-Buying-Guide-Making-Sure-You-Get-a-Good-One-03.png'  />
<br><br><br>
<img class="img-atr" data-src='https://static.pexels.com/photos/120049/pexels-photo-120049.jpeg'  />
<br><br><br>
<img class="img-atr" data-src='https://www.u2j.org/wp-content/uploads/2014/03/ceiling-lights-indoor-light-light-bulbs-christmas-lights-bathroom-light-fixtures-light-led-lighting-room-lights-heavenly-led-lights-for-growing-plants-green-led-lights-for-carsled-glow-lights-for.jpg'  />
<br><br><br>