Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active November 22, 2023 01:17
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kristoferjoseph/c4e47389ae0f0447db175b914e471628 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/c4e47389ae0f0447db175b914e471628 to your computer and use it in GitHub Desktop.
Single file Web Component
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Single File Web Component</title>
</head>
<body>
<template id=single-file>
<style>
h1 {
color: red;
}
</style>
<h1>Hello World</h1>
<script type=module>
class HelloWorld extends HTMLElement {
constructor () {
super()
const template = document.getElementById('single-file')
this.attachShadow({ mode: 'open' })
.appendChild(template.content.cloneNode(true))
}
connectedCallback () {
console.log('Why hello there 👋')
}
}
customElements.define('hello-world', HelloWorld)
</script>
</template>
<hello-world></hello-world>
<script>
const sf = document.getElementById('single-file')
document.body.appendChild(sf.content.lastElementChild)
</script>
</body>
</html>
@Westbrook
Copy link

The polyfill is so small that it’s hard to say “no”, if this use case suits you. We just listed API as “critical” as part of the Web Component Community Group’s presentation to TPAC: https://w3c.github.io/webcomponents-cg/#declarative-shadow-dom so hopefully soon. You can check out the issues linked there for any browser specific questions or worries on this one.

@kristoferjoseph
Copy link
Author

@Westbrook That is very promising indeed. Thanks for the info!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment