Created
July 24, 2022 18:27
-
-
Save virtueer/61e3c3f5adbea4eeffb4861a24b995ca 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
async function render() { | |
const loaders = document.querySelectorAll("[xLoad]"); | |
if (loaders.length === 0) | |
return | |
for (let i = 0; i < loaders.length; i++) { | |
const element = loaders[i]; | |
const from = element.getAttribute("xLoad"); | |
const res = await fetch(from); | |
const data = await res.text(); | |
let parser = new DOMParser(); | |
const doc = parser.parseFromString(data, "text/html"); | |
const scripts = getScripts(doc.scripts) | |
const styles = getStyles(doc.body.childNodes) | |
if (styles.length !== 0) | |
document.head.appendChild(...styles) | |
removeScriptsAndStyles(doc.body.childNodes) | |
element.replaceWith(...doc.body.childNodes); | |
enableScripts(scripts) | |
} | |
render() | |
} | |
function enableScripts(scripts) { | |
for (let i = 0; i < scripts.length; i++) { | |
const script = scripts[i]; | |
document.body.appendChild(script) | |
} | |
} | |
function getStyles(nodes) { | |
const globalStyles = [] | |
for (let i = 0; i < nodes.length; i++) { | |
const node = nodes[i]; | |
if (node.tagName === 'STYLE') | |
globalStyles.push(node) | |
} | |
return globalStyles | |
} | |
function getScripts(scripts) { | |
const globalScripts = [] | |
for (let i = 0; i < scripts.length; i++) { | |
const element = scripts[i]; | |
const script = document.createElement('script') | |
script.innerHTML = element.innerHTML | |
globalScripts.push(script) | |
} | |
return globalScripts | |
} | |
function removeScriptsAndStyles(nodes) { | |
for (let i = 0; i < nodes.length; i++) { | |
const node = nodes[i]; | |
if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE') | |
node.remove() | |
} | |
} | |
window.addEventListener('load', render) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment