延迟加载始终是制作某些Web应用程序时要执行的任务,现在由于它的存在,它的实现将变得更加容易 本地延迟加载Chrome –新功能
载入属性介绍
Google新发布公告,即 镀铬76 says you can use the loading
attribute to lazy load the images and iframes without the custom lazy-loading code or any other use of the javascript library. With this new feature, it’s very easy to implement the 延迟加载 on images and iframes just by using its simple attribute.
<img src="celebration.jpg" loading="lazy" alt="..." />
<iframe src="video-player.html" loading="lazy"></iframe>
使用此属性,我们只能在图像和iframe进入视口时加载它们。
It is mandatory to add height and width attribute to the <img/>
and <iframe></iframe>
element or specify the style values directly in an inline style.
加载属性
加载属性支持三个不同的值,以延迟加载屏幕外图像和iframe,直到用户在它们附近滚动为止
lazy
:启用对图像和iframe的延迟加载。eager
:立即加载图像和iframe。auto
:浏览器将确定是否延迟加载。
<!-- DEFAULT LOADING -->
<img src="image.png" loading="默认" alt="可爱的猫" width="200" height="200">
<iframe src="//example.com" loading="默认"></iframe>
<!-- loads the resource with the 默认 browser behaviour -->
<!-- EAGER LOADING -->
<img src="image.png" loading="eager" alt="可爱的猫" width="200" height="200">
<iframe src="//example.com" loading="eager"></iframe>
<!-- loads all resources immediately on page load -->
loading='auto'
.The loading
attribute for <img>
and <iframe>
is being worked on as part of the 的HTML标准.
例子:
The loading
attribute works on <img>
(including with srcset
and inside <picture>
) as well as on <iframe>
:
<!-- Lazy-load images in <picture>. <img> is the one driving image
loading so <picture> and srcset fall off of that -->
<picture>
<source media="(min-width: 40em)" srcset="big.jpg 1x, big-hq.jpg 2x">
<source srcset="small.jpg 1x, small-hq.jpg 2x">
<img src="default.jpg" loading="lazy">
</picture>
<!-- Lazy-load an image that has srcset specified -->
<img src="small.jpg"
srcset="large.jpg 1024w, medium.jpg 640w, small.jpg 320w"
sizes="(min-width: 36em) 33.3vw, 100vw"
alt="一朵红玫瑰" loading="lazy">
在其他浏览器中
我们应该牢记跨浏览器支持的重要性。可以通过以下功能检测对加载的支持:
(async () => {
if ('loading' in 的HTMLImageElement.prototype) {
const images = document.querySelectorAll("img.lazyload");
images.forEach(img => {
img.src = img.dataset.src;
});
} else {
// Dynamically import the LazySizes library
const lazySizesLib = await import('/lazysizes.min.js');
// Initiate LazySizes (reads data-src & class=lazyload)
lazySizes.init(); // lazySizes works off a global.
}
})();
浏览器设定
但是,延迟加载功能尚未发布稳定版本,但是我们可以开始测试在chrome浏览器中启用该标记:
- 对于图像延迟加载:<
#enable-lazy-image-loading
- 对于iframe延迟加载:
#enable-lazy-frame-loading
Simply go to 铬://flags/
and search the above flags and enable them
A loading=lazy
demo featuring exactly 100 kitten pics 可用。一探究竟!