Cool idea! Since you said you were new to JavaScript, can I share some code with you:
<!-- Use Custom Elements-compatible tag name -->
<!-- Define refresh as an attribute, not a class -->
<jasna-component src="components/navbar.html" refresh="10000"></jasna-component>
<jasna-component src="components/header.html" refresh></jasna-component>
<jasna-component src="components/footer.html"></jasna-component>
<script>
async function loadContent(component) {
const url = component.getAttribute('src');
const response = await fetch(url);
// Very risky! This could lead to an XSS attack.
component.innerHTML = await response.text();
}
async function liveComponents(component) {
const refreshMs = Number(component.getAttribute('refresh'));
const sleepTime = Number.isInteger(refreshMs) ? refreshMs : 2000;
while (true) {
await new Promise(r => setTimeout(r, sleepTime));
await loadContent(component);
}
}
const components = document.getElementsByTagName('jasna-component');
for (const component of components) {
loadContent(component);
if (component.hasAttribute('refresh')) {
liveComponents(component)
}
}
</script>