|
|
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:
|
<iframe src="page1.html" loading="lazy"></iframe>
<iframe src="page2.html" loading="lazy"></iframe>
<iframe src="page3.html" loading="lazy"></iframe>For more precise control or for older browsers that don't fully support loading="lazy", you can use JavaScript to load iframes sequentially.
<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>In following has fully completed codes.
<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 |