Lazy load iframe video using IntersectionObserver
Here is the below code that will load the iframe video when it iframe will be in the viewport.
It is important that to fill the page i have used image tag with width and height.
You can use your own data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy load iframe video using IntersectionObserver</title>
</head>
<body>
<br/><img width="500" height="500" src="https://imgd.aeplcdn.com/1056x594/n/cw/ec/185315/jupiter-right-side-view-16.jpeg?isig=0&q=80" alt="Sample Image">
<br/><img width="500" height="500" src="https://imgd.aeplcdn.com/1056x594/n/cw/ec/185315/jupiter-right-side-view-16.jpeg?isig=0&q=80" alt="Sample Image">
<br/><img width="500" height="500" src="https://imgd.aeplcdn.com/1056x594/n/cw/ec/185315/jupiter-right-side-view-16.jpeg?isig=0&q=80" alt="Sample Image">
<br/><img width="500" height="500" src="https://imgd.aeplcdn.com/1056x594/n/cw/ec/185315/jupiter-right-side-view-16.jpeg?isig=0&q=80" alt="Sample Image">
<br/><img width="500" height="500" src="https://imgd.aeplcdn.com/1056x594/n/cw/ec/185315/jupiter-right-side-view-16.jpeg?isig=0&q=80" alt="Sample Image">
<iframe allowfullscreen="" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin" title="Title" url-src="PUT-YOUYUBE-VIDEO-LINK-HERE"
id="widget2" data-gtm-yt-inspected-5="true" width="640" height="360" frameborder="0"></iframe>
<script>
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const iframe = entry.target;
//iframe.src = iframe.dataset.src; // Assume if you use data-src for youtube link
iframe.src=iframe.getAttribute('url-src');
observer.unobserve(iframe);
}
});
});
const iframes = document.querySelectorAll('iframe[url-src]');
iframes.forEach(iframe => {
observer.observe(iframe);
});
</script>
</body>
</html>
0 comments:
Post a Comment