Other html stuff
Demo: the sources
**Page source:
-------------
<p>Other html stuff</p>
<!--imports-->
<div data-import="someForm"></div>
<div data-import="somethingElse"></div>
<p>Demo: the sources</p>
<hr/>
**script source:
---------------
fetchTemplates(`./templates.html`);
async function fetchTemplates(templatePath) {
return await fetch(templatePath)
.then(r => r.text())
.then(doc => Object.assign(document.createElement(`template`), {innerHTML: doc}))
.then(loadTemplates);
}
function loadTemplates(template) {
const content = template.content;
document.querySelectorAll(`[data-import]`).forEach( el => {
const importElem = content.querySelector(`#${el.dataset.import}`);
if (importElem && !el.dataset.imported) {
const hasScript = importElem.querySelector(`script`);
if (hasScript) {
document.querySelector(`body`).appendChild(
Object.assign(document.createElement(`script`), {
src: `data:text/javascript;base64,${btoa(hasScript.textContent)}`}));
}
el.appendChild(importElem.cloneNode(true));
el.dataset.imported = `ok`;
}
});
}