Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active November 12, 2021 23:03
Show Gist options
  • Save kristoferjoseph/3a29660fe51f0e5115cee829c258073e to your computer and use it in GitHub Desktop.
Save kristoferjoseph/3a29660fe51f0e5115cee829c258073e to your computer and use it in GitHub Desktop.
Multiple single file Web Components
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<template id="a">
<style>
slot {
color: red;
}
</style>
<slot></slot>
<script type=module>
class a extends HTMLElement {
constructor() {
super()
const template = document.getElementById('a')
this.attachShadow({ mode: 'open' })
.appendChild(template.content.cloneNode(true))
}
connectedCallback() {
console.log('Hello from a')
}
}
customElements.define('x-a', a)
</script>
</template>
<template id="b">
<style>
slot {
color: green;
}
</style>
<slot></slot>
<script type=module>
class b extends HTMLElement {
constructor() {
super()
const template = document.getElementById('b')
this.attachShadow({ mode: 'open' })
.appendChild(template.content.cloneNode(true))
}
connectedCallback() {
console.log('Hello from b')
}
}
customElements.define('x-b', b)
</script>
</template>
<template id="c">
<style>
slot {
color: blue;
}
</style>
<slot></slot>
<script type=module>
class c extends HTMLElement {
constructor() {
super()
const template = document.getElementById('c')
this.attachShadow({ mode: 'open' })
.appendChild(template.content.cloneNode(true))
}
connectedCallback() {
console.log('Hello from c')
}
}
customElements.define('x-c', c)
</script>
</template>
<template id="d">
<style>
slot {
color: purple;
}
</style>
<slot></slot>
<script type="module" src="/d.js"></script>
</template>
<x-a>A</x-a>
<x-b>B</x-b>
<x-c>C</x-c>
<x-d>D</x-d>
<script>
Array.from(document.getElementsByTagName("template")).forEach(t => 'SCRIPT' === t.content.lastElementChild.nodeName?document.body.appendChild(t.content.lastElementChild):'')
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment