Skip to content

Instantly share code, notes, and snippets.

@thescientist13
Created May 10, 2022 01:56
Show Gist options
  • Save thescientist13/67dbcc2ec950f1c7433a10f05cf2766d to your computer and use it in GitHub Desktop.
Save thescientist13/67dbcc2ec950f1c7433a10f05cf2766d to your computer and use it in GitHub Desktop.
getInnerHTML clarification

To quote from the web.dev article on serializing Declarative Shadow DOM

Passing the includeShadowRoots:true option serializes the entire subtree of an element, including its shadow roots. The included shadow roots are serialized using the <template shadowroot> syntax.

In the context of server side renderinbg (SSR), I'm not sure if it is saying that if it was set to false a) It would not literally does not render shadow roots at all b) just doesn't render / return them in <template>

So for example, given these custom elements + shadowRoot

// navigation.js
const template = document.createElement('template');

template.innerHTML = `
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about">About</a></li>
      <li><a href="/contact">Contact</a></li>
    <ul>
  </nav>
`;

class Navigation extends HTMLElement {
  connectedCallback() {
    if (!this.shadowRoot) {
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
  }
}

customElements.define('wcc-navigation', Navigation);

// header.js
const template = document.createElement('template');

template.innerHTML = `
  <header>
    <h1>Welcome to my website</h1>
    <wcc-navigation></wcc-navigation>
  </header>
`;

class Header extends HTMLElement {
  connectedCallback() {
    if (!this.shadowRoot) {
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
  }
}

And used as so

import './navigation.js'
import { Header } from './header.js';

const element = new Header();
const html = element.getInnerHTML({ includeShadowRoots: false });

console.debug({ html });

Would the output be

A) No Shadow Roots

<header>
  <h1>Welcome to my website</h1>
</header>

or

B) Just no <template> (e.g. only light DOM)

<header>
  <h1>Welcome to my website</h1>
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about">About</a></li>
      <li><a href="/contact">Contact</a></li>
    <ul>
  </nav>
</header>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment