Created
May 19, 2023 03:01
-
-
Save megarubber/909ce1263a4758eaef9176604e46aba6 to your computer and use it in GitHub Desktop.
Repeat a HTML element for multiple pages, using vanilla JS
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
<include src="path_to_your_html_file"></include> | |
<script type="text/javascript"> | |
async function includeHTML() { | |
const includes = document.getElementsByTagName('include'); | |
[].forEach.call(includes, include => { | |
let filePath = include.getAttribute('src'); | |
fetch(filePath).then((file) => { | |
file.text().then((content) => { | |
include.insertAdjacentHTML('afterend', content); | |
include.remove(); | |
}); | |
}); | |
}); | |
}; | |
includeHTML(); | |
// Using with DOM manipulation | |
function waitForElm(selector) { | |
return new Promise(resolve => { | |
if (document.querySelector(selector)) { | |
return resolve(document.querySelector(selector)); | |
} | |
const observer = new MutationObserver(mutations => { | |
if (document.querySelector(selector)) { | |
resolve(document.querySelector(selector)); | |
observer.disconnect(); | |
} | |
}); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true | |
}); | |
}); | |
// And use async functions when use the document.getElementSomething... | |
waitForElm('.mobile-menu').then((elm) => { }); | |
} | |
</script> | |
<!-- Credits: W3Schools --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment