SlideShare a Scribd company logo
The Time for Vanilla Web
Components has Arrived
Gil Fink
sparXys CEO, @gilfink
We all love <div> soup
We all love <div> soup
3
Known website markup…
What if…
There’s an <element> for that
About Me
• sparXys CEO and senior consultant
• Microsoft MVP in the last 9 years
• Pro Single Page Application Development (Apress) co-author
• 4 Microsoft Official Courses (MOCs) co-author
• GDG Rishon and AngularUP co-organizer
Agenda
• The Problems We Faced
• Web Components APIs
• Templates
• Imports
• Shadow DOM
• Custom Elements
1. Undescriptive Markup
Markup Example
2. Poor Separation of Concerns
You want HTML, CSS and
JavaScript to work together
You end up with a mess
3. No Native Templates
• Store HTML in hidden DOM element and show it
• Use script tag as a template holder:
<script id=”myTemplate” type=”text/template”>
<div>
…
</div>
</script>
4. Bundling is Hard
• You want to bundle a complex component
The component includes HTML, CSS and JavaScript
how would you do that?
• Use a server side mechanism?
• Bundler? (Webpack/Browserify)
Can we do better?
What if we could teach the
browser new elements?
Each Element Instance
• Will be a DOM element
• Creates its own DOM tree
• Can be accessed and manipulated using DOM functions or its own
API
• Is a JavaScript object
• Is this possible?
Web Components to the Rescue
• Natively-supported, standardized JavaScript components
• Some general goals:
Code Reuse Encapsulation
Separation of
Concerns
Composition Theming Expressive Semantic
The Web Components Standard
• Reusable DOM fragmentsTemplates
• Load HTML declarativelyImports
• DOM encapsulationShadow DOM
• Create your own elements
Custom
Elements
Web Components API Support
• We need Polyfills in some browsers
Setting The Environment
• We will use the webcomponents.js Polyfill
• A real world tested Polyfill
• Download:
• https://github.com/webcomponents/webcomponentsjs/
• Or install using your favorite package manager
• Make sure the Polyfill script runs first
Demo
Setting the environment
Let’s Drill Down
Templates
• HTML element – template
• Can be used to instantiate document fragments
• Can wrap HTML, style tags and script tags
• No data binding support out of the box!
<template id=”myTemplate”>
<div>
…
</div>
</template>
Cloning a Template
• Select the template and extract its content
• Using its content property
• Use the importNode function to get the cloned content
• Only when the clone is appended to the DOM
• The style and JavaScript are executed
• Resources like images are retrieved from the server
Cloning a Template - Example
<template id=”myTemplate”>
…
</template>
// check template support
if ('content' in document.createElement('template')) {
// get the template
let template = document.getElementById(‘myTemplate’);
// clone the template
let clone = document.importNode(template.content, true);
// use the clone
elm.appendChild(clone);
}
Templates
Demo
The Slot Element
• Placeholder inside a web component
• Lets you inject separate DOM trees inside a component
• Named slot is used to expose more then one slot in a component
• Can be partnered with template elements
Combining Slot and Template Elements
<template id=”myTemplate”>
<div>
<slot name=“header"></slot>
<slot name="description"></slot>
</div>
</template>
Imports
• Load additional HTML documents
• Without using Ajax
• A new type of link tag
• Use the rel attribute with the import type:
<link rel=”import” href=”myImport.html”>
Imports and Bundling
• HTML Imports are intended to be used as packaging mechanism
• Enable to bundle a full component into one HTML file
• The HTML can include scripts and CSS styles
• The whole bundle can be retrieved in one single call
Imports and The DOM
• Importing a document doesn’t include it into the DOM
• It will parse it in memory and load all the additional resources
• Use the import property of the link tag:
let content = document.querySelector(‘link[rel=”import”]’).import;
Imports
Demo
Import Additional Notes
• Scripts running inside the import can reference the containing
document by calling document.currentScript.ownerDocument
• CORS constraints apply to documents imported from other domains
A Few Words About Script Modules
• Scripts that are treated as ECMAScript modules
• Module scripts don’t block the HTML parser
• Resembles script defer attribute
• Already implemented in most of the browsers
• Probably will replace the import standard
<script type=“module”>
import {someFunc} from './utils.js';
someFunc('Modules are pretty cool.');
</script>
Shadow DOM
• Encapsulate DOM parts
• The browser will know how to present those parts
• The browser won’t show the encapsulated parts in the source code
• Creates a boundary between the component and its user
The Problems Shadow DOM Tries to Solve
• Components/widgets encapsulation
• Style leakage
• Leaks from one component to another
• Leaks from imported 3th party library/framework
• Global DOM
• id or class attributes all over the place
Shadow DOM in The Browser
<video src="media/myVideo.mp4" controls></video>
<input type="date">
Show Shadow DOM Elements in
Chrome
Demo
Shadow DOM – Cont.
• Use the attachShadow function to wrap an element as a shadow root:
• Mode property:
• open - elements of the shadow root are accessible from the outside using
element.shadowRoot
• closed - denies any access to node(s) inside the shadow root
let host = document.getElementByIt(‘shadowDOMHost’);
let root = host.attachShadow({mode: 'open'});
root.innerHTML = ‘<div>Lurking in the shadows</div>’;
Styling Shadow DOM
• Shadow DOM can have inline styles
• Using :host, :host() and :host-context pseudo-classes
• ::slotted() pseudo-element
<div name="myElement">
<style>
:host {
border: 1px solid lightgray;
}
</style>
<template>...</template>
</div>
Shadow DOM
Demo
Custom Elements
• Enable to extend or create custom HTML elements
• Defined using the customElements.define function:
or extend an existing element:
let myInput = window.customElements.define(‘my-input’,
class x extends HTMLElement {…});
let myInput = window.customElements.define(‘my-input’,
class y extends HTMLInputElement {...});
Custom Elements – Naming
• You can create named elements (almost) any way you want:
• Same naming rules as other HTML tags
• There must be a dash (“-”) in the name
• To future-proof the name against the HTML standard
• To avoid naming collisions
Custom Elements – Usage
• Use the element in your DOM:
or use the createElement function:
<my-input></my-input>
let elm = document.createElement(‘my-input’);
Custom Element Life Cycle Events
• connectedCallback
• disconnectedCallback
• attributeChangedCallback
• adoptedCallback
class MyInput extends HTMLElement {
constructor() {
super();
// your initialization code goes here
}
connectedCallback() {…}
disconnectedCallback() {…}
attributeChangedCallback() {…}
adoptedCallback() {…}
}
Observing Attribute Changes
• First list all the observed properties
• Use the observedAttributes getter
• Wire the attributeChangedCallback
• Will be called for every attribute that changes
class MyInput extends HTMLElement {
constructor() {
super();
// your initialization code goes here
}
static get observedAttributes() {
return ['attrName'];
}
attributeChangedCallback(name, oldValue, newValue) {
…
}
}
customElements Registry
• Includes API to
• Define custom elements using the define function
• Get custom element definition using the get function
• Understand if a custom element is defined using the whenDefined function
• Useful to defer work until the elements are really defined
Custom Elements
Demo
The Current State of Web Components
• Still not a recommendation (yet)
• Browser support:
http://caniuse.com/#search=web%20components
• Known web component libraries:
Polymer X-Tag Stencil Slim.js Skate.js
Summary
• Web Components are emerging standards that enable:
• Encapsulation
• Separation of Concerns
• Element portability
• And more
• They are still in development!
Questions?
#UseThePlatform
Thank You!

More Related Content

PDF
Web Components - The Future is Here
PDF
Build Reusable Web Components using HTML5 Web cComponents
PDF
Web components
PDF
Component-Oriented Web Development with Dart
PDF
Custom Elements with Polymer Web Components #econfpsu16
PDF
Web component driven development
PDF
Building search app with ElasticSearch
PDF
Web Components Everywhere
Web Components - The Future is Here
Build Reusable Web Components using HTML5 Web cComponents
Web components
Component-Oriented Web Development with Dart
Custom Elements with Polymer Web Components #econfpsu16
Web component driven development
Building search app with ElasticSearch
Web Components Everywhere

What's hot (20)

PDF
[2015/2016] Require JS and Handlebars JS
PPTX
Getting started with jQuery
PPTX
Introduction to jQuery
PPTX
Web Components
PDF
Angular - Chapter 7 - HTTP Services
PDF
Stencil the time for vanilla web components has arrived
PDF
Sightly - AEM6 UI Development using JS and JAVA
PDF
JavaScript
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
PDF
JavaScript - Chapter 3 - Introduction
PDF
Angular - Chapter 5 - Directives
PDF
Web components the future is here
PPT
Getting started with angular js
PDF
[2015/2016] JavaScript
PDF
Web Components
PPTX
Polymer and web component
PDF
Angular - Chapter 4 - Data and Event Handling
PPTX
Google Developer Group(GDG) DevFest Event 2012 Android talk
PPTX
Web Components
PDF
HTML5 & CSS3 refresher for mobile apps
[2015/2016] Require JS and Handlebars JS
Getting started with jQuery
Introduction to jQuery
Web Components
Angular - Chapter 7 - HTTP Services
Stencil the time for vanilla web components has arrived
Sightly - AEM6 UI Development using JS and JAVA
JavaScript
2011 NetUG HH: ASP.NET MVC & HTML 5
JavaScript - Chapter 3 - Introduction
Angular - Chapter 5 - Directives
Web components the future is here
Getting started with angular js
[2015/2016] JavaScript
Web Components
Polymer and web component
Angular - Chapter 4 - Data and Event Handling
Google Developer Group(GDG) DevFest Event 2012 Android talk
Web Components
HTML5 & CSS3 refresher for mobile apps
Ad

Similar to The Time for Vanilla Web Components has Arrived (20)

PPTX
Web components
PPTX
WEB TECHNOLOGY Unit-4.pptx
PDF
Stencil: The Time for Vanilla Web Components has Arrived
PPTX
Web components, so close!
PPTX
Web components
PDF
Web Components v1
PPTX
Dom date and objects and event handling
PPTX
Internet protocol second unit IIPPT.pptx
PDF
Client-side JavaScript
PPTX
Html,CSS & UI/UX design
PDF
Agile sites311training
PPT
Joomla Beginner Template Presentation
PPTX
Fundamentals of HTML5
PPTX
Creating Custom Templates for Joomla! 2.5
PDF
Advanced guide to develop ajax applications using dojo
PDF
Intro JavaScript
PPTX
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
PDF
Stencil the time for vanilla web components has arrived
PDF
Web components - The Future is Here
PDF
Javascript libraries
Web components
WEB TECHNOLOGY Unit-4.pptx
Stencil: The Time for Vanilla Web Components has Arrived
Web components, so close!
Web components
Web Components v1
Dom date and objects and event handling
Internet protocol second unit IIPPT.pptx
Client-side JavaScript
Html,CSS & UI/UX design
Agile sites311training
Joomla Beginner Template Presentation
Fundamentals of HTML5
Creating Custom Templates for Joomla! 2.5
Advanced guide to develop ajax applications using dojo
Intro JavaScript
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
Stencil the time for vanilla web components has arrived
Web components - The Future is Here
Javascript libraries
Ad

More from Gil Fink (20)

PDF
Becoming a Tech Speaker
PPTX
Web animation on steroids web animation api
PDF
Stencil the time for vanilla web components has arrived
PDF
Being a tech speaker
PDF
Working with Data in Service Workers
PDF
Demystifying Angular Animations
PDF
Redux data flow with angular
PDF
Redux data flow with angular
PDF
Who's afraid of front end databases?
PDF
One language to rule them all type script
PDF
End to-end apps with type script
PDF
Redux data flow with angular 2
PDF
Biological Modeling, Powered by AngularJS
PDF
Who's afraid of front end databases
PDF
Biological modeling, powered by angular js
PDF
Whos afraid of front end databases?
PDF
One language to rule them all type script
PDF
Getting Started with TypeScript
PDF
Biological Modeling, Powered by AngularJS
PDF
Biological Modelling, Powered by AngularJS
Becoming a Tech Speaker
Web animation on steroids web animation api
Stencil the time for vanilla web components has arrived
Being a tech speaker
Working with Data in Service Workers
Demystifying Angular Animations
Redux data flow with angular
Redux data flow with angular
Who's afraid of front end databases?
One language to rule them all type script
End to-end apps with type script
Redux data flow with angular 2
Biological Modeling, Powered by AngularJS
Who's afraid of front end databases
Biological modeling, powered by angular js
Whos afraid of front end databases?
One language to rule them all type script
Getting Started with TypeScript
Biological Modeling, Powered by AngularJS
Biological Modelling, Powered by AngularJS

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Modernizing your data center with Dell and AMD
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation theory and applications.pdf
Modernizing your data center with Dell and AMD
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Machine learning based COVID-19 study performance prediction
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Understanding_Digital_Forensics_Presentation.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
NewMind AI Monthly Chronicles - July 2025
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Unlocking AI with Model Context Protocol (MCP)
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
Diabetes mellitus diagnosis method based random forest with bat algorithm

The Time for Vanilla Web Components has Arrived

  • 1. The Time for Vanilla Web Components has Arrived Gil Fink sparXys CEO, @gilfink
  • 2. We all love <div> soup
  • 3. We all love <div> soup 3 Known website markup…
  • 6. About Me • sparXys CEO and senior consultant • Microsoft MVP in the last 9 years • Pro Single Page Application Development (Apress) co-author • 4 Microsoft Official Courses (MOCs) co-author • GDG Rishon and AngularUP co-organizer
  • 7. Agenda • The Problems We Faced • Web Components APIs • Templates • Imports • Shadow DOM • Custom Elements
  • 9. 2. Poor Separation of Concerns You want HTML, CSS and JavaScript to work together You end up with a mess
  • 10. 3. No Native Templates • Store HTML in hidden DOM element and show it • Use script tag as a template holder: <script id=”myTemplate” type=”text/template”> <div> … </div> </script>
  • 11. 4. Bundling is Hard • You want to bundle a complex component The component includes HTML, CSS and JavaScript how would you do that? • Use a server side mechanism? • Bundler? (Webpack/Browserify)
  • 12. Can we do better?
  • 13. What if we could teach the browser new elements?
  • 14. Each Element Instance • Will be a DOM element • Creates its own DOM tree • Can be accessed and manipulated using DOM functions or its own API • Is a JavaScript object • Is this possible?
  • 15. Web Components to the Rescue • Natively-supported, standardized JavaScript components • Some general goals: Code Reuse Encapsulation Separation of Concerns Composition Theming Expressive Semantic
  • 16. The Web Components Standard • Reusable DOM fragmentsTemplates • Load HTML declarativelyImports • DOM encapsulationShadow DOM • Create your own elements Custom Elements
  • 17. Web Components API Support • We need Polyfills in some browsers
  • 18. Setting The Environment • We will use the webcomponents.js Polyfill • A real world tested Polyfill • Download: • https://github.com/webcomponents/webcomponentsjs/ • Or install using your favorite package manager • Make sure the Polyfill script runs first
  • 21. Templates • HTML element – template • Can be used to instantiate document fragments • Can wrap HTML, style tags and script tags • No data binding support out of the box! <template id=”myTemplate”> <div> … </div> </template>
  • 22. Cloning a Template • Select the template and extract its content • Using its content property • Use the importNode function to get the cloned content • Only when the clone is appended to the DOM • The style and JavaScript are executed • Resources like images are retrieved from the server
  • 23. Cloning a Template - Example <template id=”myTemplate”> … </template> // check template support if ('content' in document.createElement('template')) { // get the template let template = document.getElementById(‘myTemplate’); // clone the template let clone = document.importNode(template.content, true); // use the clone elm.appendChild(clone); }
  • 25. The Slot Element • Placeholder inside a web component • Lets you inject separate DOM trees inside a component • Named slot is used to expose more then one slot in a component • Can be partnered with template elements
  • 26. Combining Slot and Template Elements <template id=”myTemplate”> <div> <slot name=“header"></slot> <slot name="description"></slot> </div> </template>
  • 27. Imports • Load additional HTML documents • Without using Ajax • A new type of link tag • Use the rel attribute with the import type: <link rel=”import” href=”myImport.html”>
  • 28. Imports and Bundling • HTML Imports are intended to be used as packaging mechanism • Enable to bundle a full component into one HTML file • The HTML can include scripts and CSS styles • The whole bundle can be retrieved in one single call
  • 29. Imports and The DOM • Importing a document doesn’t include it into the DOM • It will parse it in memory and load all the additional resources • Use the import property of the link tag: let content = document.querySelector(‘link[rel=”import”]’).import;
  • 31. Import Additional Notes • Scripts running inside the import can reference the containing document by calling document.currentScript.ownerDocument • CORS constraints apply to documents imported from other domains
  • 32. A Few Words About Script Modules • Scripts that are treated as ECMAScript modules • Module scripts don’t block the HTML parser • Resembles script defer attribute • Already implemented in most of the browsers • Probably will replace the import standard <script type=“module”> import {someFunc} from './utils.js'; someFunc('Modules are pretty cool.'); </script>
  • 33. Shadow DOM • Encapsulate DOM parts • The browser will know how to present those parts • The browser won’t show the encapsulated parts in the source code • Creates a boundary between the component and its user
  • 34. The Problems Shadow DOM Tries to Solve • Components/widgets encapsulation • Style leakage • Leaks from one component to another • Leaks from imported 3th party library/framework • Global DOM • id or class attributes all over the place
  • 35. Shadow DOM in The Browser <video src="media/myVideo.mp4" controls></video> <input type="date">
  • 36. Show Shadow DOM Elements in Chrome Demo
  • 37. Shadow DOM – Cont. • Use the attachShadow function to wrap an element as a shadow root: • Mode property: • open - elements of the shadow root are accessible from the outside using element.shadowRoot • closed - denies any access to node(s) inside the shadow root let host = document.getElementByIt(‘shadowDOMHost’); let root = host.attachShadow({mode: 'open'}); root.innerHTML = ‘<div>Lurking in the shadows</div>’;
  • 38. Styling Shadow DOM • Shadow DOM can have inline styles • Using :host, :host() and :host-context pseudo-classes • ::slotted() pseudo-element <div name="myElement"> <style> :host { border: 1px solid lightgray; } </style> <template>...</template> </div>
  • 40. Custom Elements • Enable to extend or create custom HTML elements • Defined using the customElements.define function: or extend an existing element: let myInput = window.customElements.define(‘my-input’, class x extends HTMLElement {…}); let myInput = window.customElements.define(‘my-input’, class y extends HTMLInputElement {...});
  • 41. Custom Elements – Naming • You can create named elements (almost) any way you want: • Same naming rules as other HTML tags • There must be a dash (“-”) in the name • To future-proof the name against the HTML standard • To avoid naming collisions
  • 42. Custom Elements – Usage • Use the element in your DOM: or use the createElement function: <my-input></my-input> let elm = document.createElement(‘my-input’);
  • 43. Custom Element Life Cycle Events • connectedCallback • disconnectedCallback • attributeChangedCallback • adoptedCallback class MyInput extends HTMLElement { constructor() { super(); // your initialization code goes here } connectedCallback() {…} disconnectedCallback() {…} attributeChangedCallback() {…} adoptedCallback() {…} }
  • 44. Observing Attribute Changes • First list all the observed properties • Use the observedAttributes getter • Wire the attributeChangedCallback • Will be called for every attribute that changes class MyInput extends HTMLElement { constructor() { super(); // your initialization code goes here } static get observedAttributes() { return ['attrName']; } attributeChangedCallback(name, oldValue, newValue) { … } }
  • 45. customElements Registry • Includes API to • Define custom elements using the define function • Get custom element definition using the get function • Understand if a custom element is defined using the whenDefined function • Useful to defer work until the elements are really defined
  • 47. The Current State of Web Components • Still not a recommendation (yet) • Browser support: http://caniuse.com/#search=web%20components • Known web component libraries: Polymer X-Tag Stencil Slim.js Skate.js
  • 48. Summary • Web Components are emerging standards that enable: • Encapsulation • Separation of Concerns • Element portability • And more • They are still in development!