Last active
September 11, 2019 06:49
-
-
Save TokenChingy/0ea3c3d1809af884bbf5b196f1a79a93 to your computer and use it in GitHub Desktop.
A lightweight component template engine.
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
(async () => { | |
const head = document.querySelector('head'); | |
const body = document.querySelector('body'); | |
const includes = document.querySelectorAll('include'); | |
const parser = new DOMParser(); | |
const templates = { | |
styles: [], | |
scripts: [], | |
} | |
for await (let include of includes) { | |
try { | |
const file = await fetch(include.dataset.src); | |
const content = parser.parseFromString(await file.text(), 'text/html'); | |
const template = document.createElement('div'); | |
template.innerHTML = content.querySelector('template').innerHTML; | |
templates.styles.push(content.querySelector('style').innerHTML); | |
templates.scripts.push(content.querySelector('script').innerHTML); | |
include.parentNode.replaceChild(template, include); | |
} catch (error) { | |
throw new Error(error); | |
} | |
} | |
const style = document.createElement('style'); | |
const script = document.createElement('script'); | |
style.innerHTML = templates.styles.join(''); | |
script.innerHTML = templates.scripts.join(''); | |
head.appendChild(style); | |
body.appendChild(script); | |
})(); | |
/** | |
index.html: | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title></title> | |
</head> | |
<body> | |
<include data-src="component.html"></include> | |
<script src="./template.js" type="text/javascript"></script> | |
</body> | |
</html> | |
component.html: | |
<template> | |
<h1>Hello World!</h1> | |
</template> | |
<script> | |
console.log('Hello World!') | |
</script> | |
<style> | |
h1 { | |
color: red; | |
} | |
</style> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment