WebComponent HTML render
by amindunited
HTML
<component-one></component-one>
<component-two><component-three></component-three></component-two>
CSS
component-one,
component-two,
component-three {
background-color: rgba(66, 66, 66, .2);
padding: 8px;
border: solid 1px grey;
margin: 8px;
display: block;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,"Fira Sans","Droid Sans","Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
}
JavaScript
/**
* Creates a Contextual Fragment and
*/
function renderHTML (content, parent, replaceContent = true) {
const range = document.createRange();
const documentFragment = range.createContextualFragment(content);
const parentContent = parent.child;
if (parentContent && replaceContent) {
parent.replaceChild(documentFragment, parent.child);
} else {
parent.appendChild(documentFragment);
}
}
/**
* Component One
*/
class ComponentOne extends HTMLElement {
constructor () {
super();
this.shadow = this.attachShadow({mode: 'open'});
}
render () {
const content = `<div>Component One Content</div>`;
renderHTML.bind(this)(content, this.shadow);
}
connectedCallback () {
this.render();
}
}
/**
* Component Two
*/
class ComponentTwo extends HTMLElement {
constructor () {
super();
// this.shadow = this.attachShadow({mode: 'open'});
}
render () {
const content = `<div><div>Component Two Content</div><slot></slot></div>`;
// renderHTML.bind(this)(content, this);
// this.shadow.appendChild(document.createElement('slot'));
this.innerHTML = `<div><h2>Above</h2><slot></slot></div>`
}
connectedCallback () {
this.render();
}
}
/**
* Component Three
*/
class ComponentThree extends HTMLElement {
constructor () {
super();
this.shadow = this.attachShadow({mode: 'open'});
}
render () {
const content = `<div>Component Three Content</div>`;
renderHTML.bind(this)(content, this.shadow);
}
connectedCallback () {
this.render();
}
}
customElements.define('component-one', ComponentOne);
customElements.define('component-two', ComponentTwo);
customElements.define('component-three', ComponentThree);