Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>
@simonw

This comment has been minimized.

Copy link

@simonw simonw commented Oct 28, 2021

This is brilliant! I spent some time playing with it to figure out exactly how it works and an annotated version with my notes here: https://gist.github.com/simonw/2df444ce0bd75c8bf91beb7a6516ba5b

@Westbrook

This comment has been minimized.

Copy link

@Westbrook Westbrook commented Oct 28, 2021

Theorized an alternate version as well: https://codepen.io/Westbrook/pen/RwZgpmg?editors=1001

@kristoferjoseph

This comment has been minimized.

Copy link
Owner Author

@kristoferjoseph kristoferjoseph commented Nov 1, 2021

@simonw Really like your annotated version!

@kristoferjoseph

This comment has been minimized.

Copy link
Owner Author

@kristoferjoseph kristoferjoseph commented Nov 1, 2021

@Westbrook I was thinking about that! Just wasn't sure when it would be generally available in all browsers.
Any idea?
This was the document I saw btw:
https://www.chromestatus.com/feature/5191745052606464

Looks like Chrome and possibly firefox but probably not safari :?

@Westbrook

This comment has been minimized.

Copy link

@Westbrook Westbrook commented Nov 1, 2021

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

This comment has been minimized.

Copy link
Owner Author

@kristoferjoseph kristoferjoseph commented Nov 2, 2021

@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