Skip to content

Instantly share code, notes, and snippets.

@matthewp
Last active January 16, 2020 18:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matthewp/f45306dcdf00b0fe2848ad6f07b6cd5f to your computer and use it in GitHub Desktop.
Save matthewp/f45306dcdf00b0fe2848ad6f07b6cd5f to your computer and use it in GitHub Desktop.
SSR web components
<!doctype html>
<html lang="en">
<title>Web component SSR</title>
<script>
customElements.define("shadow-root",class extends HTMLElement{connectedCallback(){let a=this.parentNode,b=a.firstElementChild;this.remove(),a.attachShadow({mode:"open"}).append(b.content.cloneNode(!0))}});
</script>
<a-component>
<template>
<header>
<slot name="header"></slot>
</header>
<section>
<p>This is a paragraph.</p>
</section>
</template>
<shadow-root></shadow-root>
<h1 slot="header">Hello world</h1>
</a-component>
<section>More text down here.</section>
<!doctype html>
<html lang="en">
<title>Web component SSR</title>
<script>
customElements.define('shadow-root', class extends HTMLElement {
connectedCallback() {
let p = this.parentNode, t = p.firstElementChild;
this.remove();
p.attachShadow({ mode: 'open' }).append(t.content.cloneNode(true));
}
});
</script>
<a-component>
<template>
<header>
<slot name="header"></slot>
</header>
<section>
<p>This is a paragraph.</p>
</section>
</template>
<shadow-root></shadow-root>
<h1 slot="header">Hello world</h1>
</a-component>
<section>More text down here.</section>

This demonstrates SSRing web components using 2 features, templates and customElements. A template is used to represent the content that should be placed in the shadowRoot. A custom element named shadow-root is used to inject the template content into the parentNode which is the shadow host.

This results in no flash of unstyled content. No CSS rewriting is necessary. The JavaScript minifys down to 205 bytes.

The downside is that it will not work with JavaScript disabled.

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