Horje
How to load iframe one by one
Loading iframes one by one, also known as sequential or deferred loading, can improve page performance and user experience, especially when dealing with multiple iframes or iframes containing heavy content. This approach prevents all iframes from loading simultaneously, which can block the main page's rendering and make the page feel slow.
Here are a few methods to achieve one-by-one iframe loading:

Lazy Loading with the loading attribute

The most straightforward and recommended method for modern browsers is to use the loading="lazy" attribute on your iframe tags. This tells the browser to defer loading of offscreen iframes until the user scrolls near them.
index.html
Example: HTML
<iframe src="page1.html" loading="lazy"></iframe>
<iframe src="page2.html" loading="lazy"></iframe>
<iframe src="page3.html" loading="lazy"></iframe>

JavaScript-based Sequential Loading

For more precise control or for older browsers that don't fully support loading="lazy" , you can use JavaScript to load iframes sequentially.

index.html
Example: HTML
<script>
document.addEventListener('DOMContentLoaded', function() { const iframes = document.querySelectorAll('iframe.deferred-load'); let currentIndex = 0; function loadNextIframe() { if (currentIndex < iframes.length) { const iframe = iframes[currentIndex]; const src = iframe.dataset.src; // Store the actual src in a data attribute if (src) { iframe.src = src; iframe.onload = function() { currentIndex++; loadNextIframe(); }; } else { // If no src is defined for some reason, just move to the next currentIndex++; loadNextIframe(); } } } // Initialize the first iframe load loadNextIframe();
});
</script>

HTML for JavaScript method:

index.html
Example: HTML
<iframe class="deferred-load" data-src="page1.html"></iframe>
<iframe class="deferred-load" data-src="page2.html"></iframe>
<iframe class="deferred-load" data-src="page3.html"></iframe>

HTML Iframe load one after one

In following has fully completed codes.

index.html
Example: HTML
<script>
document.addEventListener('DOMContentLoaded', function() { const iframes = document.querySelectorAll('iframe.deferred-load'); let currentIndex = 0; function loadNextIframe() { if (currentIndex < iframes.length) { const iframe = iframes[currentIndex]; const src = iframe.dataset.src; // Store the actual src in a data attribute if (src) { iframe.src = src; iframe.onload = function() { currentIndex++; loadNextIframe(); }; } else { // If no src is defined for some reason, just move to the next currentIndex++; loadNextIframe(); } } } // Initialize the first iframe load loadNextIframe();
});
</script>
<iframe class="deferred-load" data-src="page1.html"></iframe>
<iframe class="deferred-load" data-src="page2.html"></iframe>
<iframe class="deferred-load" data-src="page3.html"></iframe>




html tips

Type :
Develop
Category :
Web Tutorial
Sub Category :
HTML Iframe Tutorial
Uploaded by :
Admin