我有一个充满图像的网站,但网站性能非常糟糕。我想让图像加载模糊,然后在滚动事件时图像将被双向加载。我正在使用 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>
1 回答
慕标琳琳
TA贡献1830条经验 获得超9个赞
如今,更常见的是 javascript 是自重。花时间解压缩,解析和编译 - 更大的图像有时可能会更快。
还有一些替代方法,例如使用loading="lazy"仅加载视口中的内容。不需要javascript!也更 SEO 友好。
<img src="image.jpg" loading="lazy" alt="..." /> <iframe src="video-player.html" loading="lazy"></iframe>
还要看一下请求标头,看看他们在请求什么。
浏览器正在发送
accept-type一堆格式。与 jpg 相比,WebP 可能会减少更多的大小,并且在有损压缩下仍然看起来不错。他们也可能会发送
Save-Data请求标头以更喜欢减小大小而不是速度,也许会为他们提供较小的图像,然后再进行升级。有些甚至发送客户端提示,如 Accept-CH: DPR, Width, Viewport-Width
坦率地说,我已经在我的手机勇敢浏览器中禁用了 javascript,因为一直有很多垃圾显示。cookie 通知、广告、订阅、权限请求,所以我更喜欢你刚刚使用loading="lazy"
您还可以查看响应式图像的 srcset https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
- 1 回答
- 0 关注
- 162 浏览
添加回答
举报
0/150
提交
取消
