猿问

如何为您的网站制作模糊的延迟图像加载?

我有一个充满图像的网站,但网站性能非常糟糕。


我想让图像加载模糊,然后在滚动事件时图像将被双向加载。


我正在使用 PHP 和 Zend 框架


我正在寻找帮助我制作延迟加载图像的 java 脚本库或 php 函数,但我找不到一个易于使用的,因为我不想手动替换所有图像


我尝试了progressive-image.js 性能提高了一点,我的主要目标是使请求数量最少


有没有和谷歌图片一样的脚本


我看过那个代码片段


 function imageLoaded(e) {

   updateImage(e.target, 'loaded');

 }


function imageError(e) {

  updateImage(e.target, 'error');

}


function updateImage(img, classname) {

  // Add the right class:

  img.classList.add(classname);


  // Remove the data-src attribute:

  img.removeAttribute('data-src');


  // Remove both listeners:

  img.removeEventListener('load', imageLoaded);

  img.removeEventListener('error', imageError);

}


window.addEventListener('load', () => {

  Array.from(document.getElementsByTagName('img')).forEach(img => {

    const src = img.getAttribute('data-src');


    if (src) {

      // Listen for both events:

      img.addEventListener('load', imageLoaded);

      img.addEventListener('error', imageError);


      // Just to simulate a slow network:

      setTimeout(() => {

        img.setAttribute('src', src);

      }, 2000 + Math.random() * 2000);

    }

  });

})

body {

  margin: 0;

  height: 100%;

}


.images {

  width: 100%;

  height: 100%;

  background: #000;

  display: flex;

  align-items: center;

  overflow-x: scroll;

}


.margin-fix {

    border-right: 1px solid transparent;

    height: 16px;

}


img {

  width: 16px;

  height: 16px;

  margin: 0 64px;

}


img.loaded {

  width: auto;

  height: 100%;

  margin: 0;

}


img.error {

  background: red;

  border-radius: 100%;


  /* You could add a custom "error" image here using background-image */

}

  <img

    src

    data-src="https://d39a3h63xew422.cloudfront.net/wp-content/uploads/2014/07/20145029/driven-by-design-the-incomparable-lancia-stratos-1476934711918-1000x573.jpg" />


  <img

    src

    data-src="https://car-images.bauersecure.com/pagefiles/76591/1752x1168/ford_racing_puma_01.jpg?mode=max&quality=90&scale=down" />


  <img

    src

    data-src="http://doesntexist.com/image.jpg" />


  <span class="margin-fix"></span>

</div>


郎朗坤
浏览 163回答 1
1回答

慕标琳琳

如今,更常见的是 javascript 是自重。花时间解压缩,解析和编译 - 更大的图像有时可能会更快。https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/javascript-startup-optimization/还有一些替代方法,例如使用loading="lazy"仅加载视口中的内容。不需要javascript!也更 SEO 友好。<img&nbsp;src="image.jpg"&nbsp;loading="lazy"&nbsp;alt="..."&nbsp;/> <iframe&nbsp;src="video-player.html"&nbsp;loading="lazy"></iframe>还要看一下请求标头,看看他们在请求什么。浏览器正在发送accept-type一堆格式。与 jpg 相比,WebP 可能会减少更多的大小,并且在有损压缩下仍然看起来不错。他们也可能会发送Save-Data请求标头以更喜欢减小大小而不是速度,也许会为他们提供较小的图像,然后再进行升级。有些甚至发送客户端提示,如 Accept-CH: DPR, Width, Viewport-Width坦率地说,我已经在我的手机勇敢浏览器中禁用了 javascript,因为一直有很多垃圾显示。cookie 通知、广告、订阅、权限请求,所以我更喜欢你刚刚使用loading="lazy"您还可以查看响应式图像的 srcset&nbsp;https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
随时随地看视频慕课网APP
我要回答