SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JSIvano Malavolta
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQueryGill Cleeren
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryAlek Davis
 
Web Components
Web ComponentsWeb Components
Web ComponentsFITC
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Sightly - AEM6 UI Development using JS and JAVA
Sightly - AEM6 UI Development using JS and JAVASightly - AEM6 UI Development using JS and JAVA
Sightly - AEM6 UI Development using JS and JAVAYash Mody
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5Daniel Fisher
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - IntroductionWebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
Web components the future is here
Web components   the future is hereWeb components   the future is here
Web components the future is hereGil Fink
 
Polymer and web component
Polymer and web componentPolymer and web component
Polymer and web componentImam Raza
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Google Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talkGoogle Developer Group(GDG) DevFest Event 2012 Android talk
Google Developer Group(GDG) DevFest Event 2012 Android talkImam Raza
 
Web Components
Web ComponentsWeb Components
Web ComponentsFITC
 
HTML5 & CSS3 refresher for mobile apps
HTML5 & CSS3 refresher for mobile appsHTML5 & CSS3 refresher for mobile apps
HTML5 & CSS3 refresher for mobile appsIvano Malavolta
 

Tendances (20)

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

Similaire à The Time for Vanilla Web Components has Arrived

Web components
Web componentsWeb components
Web componentsNoam Kfir
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxkarthiksmart21
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedGil Fink
 
Web components, so close!
Web components, so close!Web components, so close!
Web components, so close!Aleks Zinevych
 
Web components
Web componentsWeb components
Web componentsMohd Saeed
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Dom date and objects and event handling
Dom date and objects and event handlingDom date and objects and event handling
Dom date and objects and event handlingsmitha273566
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 
Joomla Beginner Template Presentation
Joomla Beginner Template PresentationJoomla Beginner Template Presentation
Joomla Beginner Template Presentationalledia
 
Creating Custom Templates for Joomla! 2.5
Creating Custom Templates for Joomla! 2.5Creating Custom Templates for Joomla! 2.5
Creating Custom Templates for Joomla! 2.5Don Cranford
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScriptkoppenolski
 
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
Iasi code camp 12 october 2013   shadow dom - mihai bîrsanIasi code camp 12 october 2013   shadow dom - mihai bîrsan
Iasi code camp 12 october 2013 shadow dom - mihai bîrsanCodecamp Romania
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Web components - The Future is Here
Web components - The Future is HereWeb components - The Future is Here
Web components - The Future is HereGil Fink
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 

Similaire à The Time for Vanilla Web Components has Arrived (20)

Web components
Web componentsWeb components
Web components
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptx
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has Arrived
 
Web components, so close!
Web components, so close!Web components, so close!
Web components, so close!
 
Web components
Web componentsWeb components
Web components
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Dom date and objects and event handling
Dom date and objects and event handlingDom date and objects and event handling
Dom date and objects and event handling
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Html,CSS & UI/UX design
Html,CSS & UI/UX designHtml,CSS & UI/UX design
Html,CSS & UI/UX design
 
Agile sites311training
Agile sites311trainingAgile sites311training
Agile sites311training
 
Joomla Beginner Template Presentation
Joomla Beginner Template PresentationJoomla Beginner Template Presentation
Joomla Beginner Template Presentation
 
Fundamentals of HTML5
Fundamentals of HTML5Fundamentals of HTML5
Fundamentals of HTML5
 
Creating Custom Templates for Joomla! 2.5
Creating Custom Templates for Joomla! 2.5Creating Custom Templates for Joomla! 2.5
Creating Custom Templates for Joomla! 2.5
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScript
 
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
Iasi code camp 12 october 2013   shadow dom - mihai bîrsanIasi code camp 12 october 2013   shadow dom - mihai bîrsan
Iasi code camp 12 october 2013 shadow dom - mihai bîrsan
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Web components - The Future is Here
Web components - The Future is HereWeb components - The Future is Here
Web components - The Future is Here
 
Javascript libraries
Javascript librariesJavascript libraries
Javascript libraries
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 

Plus de Gil Fink

Becoming a Tech Speaker
Becoming a Tech SpeakerBecoming a Tech Speaker
Becoming a Tech SpeakerGil Fink
 
Web animation on steroids web animation api
Web animation on steroids web animation api Web animation on steroids web animation api
Web animation on steroids web animation api Gil Fink
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Being a tech speaker
Being a tech speakerBeing a tech speaker
Being a tech speakerGil Fink
 
Working with Data in Service Workers
Working with Data in Service WorkersWorking with Data in Service Workers
Working with Data in Service WorkersGil Fink
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular AnimationsGil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angularGil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angularGil Fink
 
Who's afraid of front end databases?
Who's afraid of front end databases?Who's afraid of front end databases?
Who's afraid of front end databases?Gil Fink
 
One language to rule them all type script
One language to rule them all type scriptOne language to rule them all type script
One language to rule them all type scriptGil Fink
 
End to-end apps with type script
End to-end apps with type scriptEnd to-end apps with type script
End to-end apps with type scriptGil Fink
 
Redux data flow with angular 2
Redux data flow with angular 2Redux data flow with angular 2
Redux data flow with angular 2Gil Fink
 
Biological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJSBiological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJSGil Fink
 
Who's afraid of front end databases
Who's afraid of front end databasesWho's afraid of front end databases
Who's afraid of front end databasesGil Fink
 
Biological modeling, powered by angular js
Biological modeling, powered by angular jsBiological modeling, powered by angular js
Biological modeling, powered by angular jsGil Fink
 
Whos afraid of front end databases?
Whos afraid of front end databases?Whos afraid of front end databases?
Whos afraid of front end databases?Gil Fink
 
One language to rule them all type script
One language to rule them all type scriptOne language to rule them all type script
One language to rule them all type scriptGil Fink
 
Getting Started with TypeScript
Getting Started with TypeScriptGetting Started with TypeScript
Getting Started with TypeScriptGil Fink
 
Biological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJSBiological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJSGil Fink
 
Biological Modelling, Powered by AngularJS
Biological Modelling, Powered by AngularJSBiological Modelling, Powered by AngularJS
Biological Modelling, Powered by AngularJSGil Fink
 

Plus de Gil Fink (20)

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

Dernier

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

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!