Skip to content

Instantly share code, notes, and snippets.

@dgrammatiko
Forked from matthewp/example-minified.html
Created January 16, 2020 18:00
Show Gist options
  • Save dgrammatiko/a4abc55d820f0bfb65b4df8836860289 to your computer and use it in GitHub Desktop.
Save dgrammatiko/a4abc55d820f0bfb65b4df8836860289 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