Last active
July 3, 2021 02:35
-
-
Save kvanbere/ea803c9068e60610b0353bd94b35e4dc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class ScriptFoldHandler { | |
constructor(nonce) { | |
this.nonce = nonce | |
// | |
this.aboveFoldScripts = [] | |
this.aboveFoldReady = new Promise((resolve, reject) => { | |
this.resolveAboveFoldScripts = resolve | |
}) | |
} | |
async element(element) { | |
if (element.tagName === 'title') { | |
await this.aboveFoldReady | |
this.aboveFoldScripts.forEach(script => { | |
element.after(`<script defer="defer" nonce="${nonce}" src="${script}"></script>`, { html: true }) | |
}) | |
} else if (element.tagName === 'script') { | |
const type = element.getAttribute('type') | |
if (type && type !== 'text/javascript') | |
return | |
const src = element.getAttribute('src') | |
//if (!src) | |
// return | |
this.aboveFoldScripts.push(src) | |
} | |
} | |
end(end) { | |
this.resolveAboveFoldScripts() | |
} | |
} |
This file contains hidden or 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
const FoldHandler = new ScriptFoldHandler(nonce) | |
// ... | |
const rewriter = new HTMLRewriter() | |
.on('title', FoldHandler) | |
.on('script[src]', FoldHandler) | |
// ... | |
.onDocument(FoldHandler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment