Skip to content

Instantly share code, notes, and snippets.

@TokenChingy
Last active September 11, 2019 06:49
Show Gist options
  • Save TokenChingy/0ea3c3d1809af884bbf5b196f1a79a93 to your computer and use it in GitHub Desktop.
Save TokenChingy/0ea3c3d1809af884bbf5b196f1a79a93 to your computer and use it in GitHub Desktop.
A lightweight component template engine.
(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