Skip to content

Instantly share code, notes, and snippets.

@Alfrex92
Created July 25, 2019 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alfrex92/1a5d23094b6e2cf496975fb90a0c357f to your computer and use it in GitHub Desktop.
Save Alfrex92/1a5d23094b6e2cf496975fb90a0c357f to your computer and use it in GitHub Desktop.
function* findLazyElements() {
const blocks = [
...Array.from(document.querySelectorAll("noscript.lazyload")).map(lazy =>
parseHTML(lazy.innerText).map(elem => ({ elem, parent: lazy.parentNode }))
),
...Array.from(document.querySelectorAll("template.lazyload")).map(lazy =>
Array.from(lazy.content.cloneNode(true).children)
.map(elem => ({ elem, parent: lazy.parentNode }))
.map(item => {
if (item.elem.tagName !== "SCRIPT") return item;
item.elem = Object.assign(item.elem.cloneNode(true), {
async: false
});
return item;
})
)
];
for (const block of blocks) {
yield* block;
}
}
function parseHTML(html) {
const div = document.createElement("div");
div.innerHTML = html;
return Array.from(div.children);
}
const it = findLazyElements();
requestIdleCallback(function f() {
const { value, done } = it.next();
if (done) return;
value.parent.appendChild(value.elem);
requestIdleCallback(f);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment