Searching for this I found some kinda hacky solutions on Stack Overflow which use fetch to load html/css at runtime.
Searching for this I found some kinda hacky solutions on Stack Overflow which use fetch to load html/css at runtime.
- Responding to being attached to the DOM
- Encapsulating DOM nodes (the Shadow DOM)
- Scoped styling (Shadow DOM + User defined stylesheets + CSS parts)
It is definitively not a templating engine. It doesn't provide any new APIs for creating DOM nodes, or mutating them a la React or handlebars or lit-html. Templating is basically the "next step up the stack". Using shadowDom.innerHTML = `...`; is basically a stand-in for having an actual templating engine.
There is work going on, developing a native templating system in the browser which may interest you. It's called the DOM Parts proposal and you can find info on it here: https://github.com/WICG/webcomponents/blob/gh-pages/proposal...
html`
<this is all syntax highlighted>
`Lit is a bit too "frameworky" for my taste, I generally just use vanilla classes that extend HTMLElement and have a render function that renders the lit-element template to the light dom.
Something like:
import {html, render} from 'lit-html';
class AppComponent extends HTMLElement {
connectedCallback() {
this.template = () => html`<markup here>`;
this.render();
}
render() {
if(this.template)
render(this.template(), this)
}
}
customElements.define('app-component', AppComponent);https://developer.mozilla.org/en-US/docs/Web/API/Web_compone...
Using innerHTML isn’t specific to Web Components in any way. It was and is a quick & dirty way to dynamically insert HTML.
Can you explain what you mean by that?
connectedCallback() {
this.shadow.innerHTML = `
<p>Hello from a web component!</p>
<style>
p {
color: pink;
font-weight: bold;
padding: 1rem;
border: 4px solid pink;
}
</style>
`;
}But there several alternatives:
1. Use DOM APIs (createElement).
2. Fetch the HTML as a separate resource.
3. Have the HTML in a separate file and bundle it with a bundler.
4. Use React/JSX.
5. Use a preferred templating library of your choice.
You can do whichever of these you like the most