Skip to content

Instantly share code, notes, and snippets.

@Schepp
Created June 10, 2025 21:34
Show Gist options
  • Save Schepp/f4be31e86ad3bc2c4e76bb88fd7e247f to your computer and use it in GitHub Desktop.
Save Schepp/f4be31e86ad3bc2c4e76bb88fd7e247f to your computer and use it in GitHub Desktop.
(() => {
const loadedIframes = []; // Holds { el, originalSrc }
document.addEventListener(
"load",
(event) => {
const iframe = event.target;
if (!iframe.matches('iframe[loading="lazy"]')) return;
// Store the original src if not already stored
if (!iframe.dataset.originalSrc) {
iframe.dataset.originalSrc = iframe.src;
}
// Add to the tracking queue
loadedIframes.push({ el: iframe, originalSrc: iframe.dataset.originalSrc });
// If more than 5 loaded iframes, reset the oldest one
if (loadedIframes.length > 5) {
const toReset = loadedIframes.shift();
// Unload the iframe content
toReset.el.src = 'about:blank';
// Restore src and lazy loading
setTimeout(() => {
toReset.el.loading = 'lazy';
toReset.el.src = toReset.originalSrc;
}, 50);
}
},
true // Capture phase
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment