Created
July 25, 2019 15:28
-
-
Save Alfrex92/1a5d23094b6e2cf496975fb90a0c357f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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