1. What are Web Components?
Web Components are a suite of native browser W3C standards that allow developers to create custom, reusable, and encapsulated HTML elements with their own isolated styling and behavior—without relying on external frameworks.
2. The Three Core Web Component Technologies
- Custom Elements: A set of JavaScript APIs to define custom HTML tags (e.g.,
). - Shadow DOM: An encapsulated DOM sub-tree whose CSS styles do not leak out into the main document, and whose parent page styles do not accidentally break inside the component.
- HTML Templates (
&): Inert markup declarations that are not rendered until cloned via JavaScript.
3. Creating a Simple Custom Element
// Define custom element class
class ExamTimerBadge extends HTMLElement {
connectedCallback() {
const duration = this.getAttribute("duration") || "60";
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
Time Left: ${duration} mins
`;
}
}
// Register custom HTML tag
customElements.define("exam-timer-badge", ExamTimerBadge);
Usage in HTML: