Last active
April 2, 2019 18:39
-
-
Save peerreynders/1d4396fa6eb67daac706969a6389a9ca to your computer and use it in GitHub Desktop.
Web Components in Action v6: 7.5.1 Slots without a Name (p.156)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<!-- | |
file: index.html | |
Web Components in Action MEAP v6 | |
https://livebook.manning.com/#!/book/web-components-in-action/chapter-7/v-6/comment-487676 | |
original: https://github.com/bengfarrell/webcomponentsinaction/blob/master/chapter7/7.5-slotsandtemplates/unnamedslots.html | |
#1: | |
prevent undefined custom element FOUC (flash of unstyled content) | |
#2: | |
- i.e. create shadowRoot in constructor rather than connectedCallback | |
- this.shadowRoot is automatically created - no need for separate this.root | |
https://developers.google.com/web/fundamentals/web-components/best-practices#create-your-shadow-root-in-the-constructor | |
https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot | |
> The Element.shadowRoot read-only property represents the shadow root hosted by the element. | |
> Use Element.attachShadow() to add a shadow root to an existing element. | |
--> | |
<title>Unnamed Slots Demo</title> | |
<style> | |
slots-demo:not(:defined) { | |
display: none; /* #1 */ | |
} | |
</style> | |
</head> | |
<body> | |
<slots-demo>Any content here goes in the slot</slots-demo> | |
<template> | |
<div> | |
<button>A Button</button> | |
<p> | |
Some Text | |
<br /> | |
<slot>placeholder text</slot> | |
</p> | |
</div> | |
</template> | |
<script> | |
(function() { | |
const template = document.querySelector('template') | |
class SlotsDemo extends HTMLElement { | |
constructor() { | |
super() | |
const clone = document.importNode(template.content, true) | |
// #2 | |
this.attachShadow({mode: 'open'}); | |
this.shadowRoot.appendChild(clone) | |
} | |
} | |
if (!customElements.get('slots-demo')) { | |
customElements.define('slots-demo', SlotsDemo) | |
} | |
}()) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment