懒加载
元素懒加载
Web pages often contain a large number of images, which contribute to data-usage, page-bloat and how fast a page can load. Many of these images are offscreen, requiring a user to scroll in order to view them.
Historically, to limit the impact offscreen images have on page load times, developers have needed to use a JavaScript library (like LazySizes) in order to defer fetching these images until a user scrolls near them.
Chrome 75 之后,浏览器原生地支持了 lazy 标签:
<!-- Lazy-load an offscreen image when the user scrolls near it -->
<img src="unicorn.jpg" loading="lazy" alt=".." />
<!-- Load an image right away instead of lazy-loading -->
<img src="unicorn.jpg" loading="eager" alt=".." />
<!-- Browser decides whether or not to lazy-load the image -->
<img src="unicorn.jpg" loading="auto" alt=".." />
<!-- 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-hd.jpg 2x" />
<source srcset="small.jpg 1x, small-hd.jpg 2x" />
<img src="fallback.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="A rad wolf"
loading="lazy"
/>
<!-- Lazy-load an offscreen iframe when the user scrolls near it -->
<iframe src="video-player.html" loading="lazy"></iframe>