在Chrome 76中,通过load属性添加了图像的本机延迟加载,然后进入了Firefox。我们很高兴地宣布,iframe的内联延迟加载现已标准化,并且在基于Chrome和Chromium的浏览器中也受支持。
<iframe src="https://example.com"
loading="lazy"
width="600"
height="400"></iframe>
lazy-loading iframe iframe , . , .
iframes ?
— , . , , . , , JavaScript , .
Chrome iframe Data Saver, , 2-3% , 1-2% First Contentful Paint 2% (FID) 95- .
?
loading , . :
- lazy .
- eager . .
- auto , .
*auto , Chrome. Google .
loading iframes :
<!-- iframe -->
<iframe src="https://example.com"
loading="lazy"
width="600"
height="400"></iframe>
<!-- iframe -->
<iframe src="https://example.com"
width="600"
height="400"></iframe>
<!-- loading="eager"
lazy-loading Lite Mode -->
<iframe src="https://example.com"
loading="eager"
width="600"
height="400"></iframe>
loading , , (Lite Mode), Chrome auto, , .
iframe JavaScript, iframe.loading = 'lazy':
var iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
iframe.loading = 'lazy';
document.body.appendChild(iframe);
iframe
loading , , , . ( iframe .)
Chrome , iframe :
- iframe 4 .
- display: none visibility: hidden
- iframe X Y
- loading = lazy, loading = auto.
iframe - , Chrome .
iframe?
, . :
YouTube ( ~ 500 ):
<iframe src="https://www.youtube.com/embed/YJGCZCaIZkQ"
loading="lazy"
width="560"
height="315"
frameborder="0"
allow="accelerometer; autoplay;
encrypted-media; gyroscope;
picture-in-picture"
allowfullscreen></iframe>
Instagram (> 100 ):
Instagram , iframe . iframe , . , , iframe.
Spotify ( 514 )
<iframe src="https://open.spotify.com/embed/album/1DFixLWuPkv3KT3TnV35m3"
loading="lazy"
width="300"
height="380"
frameborder="0"
allowtransparency="true"
allow="encrypted-media"></iframe>
, , .
Facebook Facebook -. , , , , … « » — , «» . Like - ( FB JSSDK) ~ 215 , 197 — JavaScript. , , , .
(Stoyan Stefanov) Facebook iframe. , , , , , . , , , . , , iframe .
, ?
, , . Chrome 77 , Lite Mode ( ) Chrome Android.
Lite Mode , . , .
, , navigator.connection.saveData, API NetworkInformation.
-? —
iframe . , loading=«lazy» iframes, iframe , , .
iframes JavaScript lazysizes. , :
- , ,
- iframe :
<script src="lazysizes.min.js" async></script> <iframe frameborder="0" class="lazyload" allowfullscreen="" width="600" height="400" data-src="//www.youtube.com/embed/ZfV-aYdU4uE"> </iframe>
, :
<iframe frameborder="0"
class="lazyload"
loading="lazy"
allowfullscreen=""
width="600"
height="400"
data-src="//www.youtube.com/embed/ZfV-aYdU4uE">
</iframe>
<script>
if ('loading' in HTMLIFrameElement.prototype) {
const iframes = document.querySelectorAll('iframe[loading="lazy"]');
iframes.forEach(iframe => {
iframe.src = iframe.dataset.src;
});
} else {
// Dynamically import the LazySizes library
const script = document.createElement('script');
script.src =
'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js';
document.body.appendChild(script);
}
</script>
内置的延迟加载iframe支持使提高网页性能变得更加容易。如果您对延迟加载有任何反馈,请随时将嵌入式iframe发布到Chromium Bug Tracker上。
感谢Addy Osmani的文章。如果您有兴趣深入了解iframe标签,请引起您的注意:有关iframe标签的全面指南