Web Components એ native browser APIs નો એક સમૂહ છે જે reusable, encapsulated custom HTML elements બનાવવા માટે છે — framework-agnostic અને standards-based. ત્રણ તકનીકો એકસાથે કામ કરે છે:
Web Components એ native browser APIs નો એક સમૂહ છે જે reusable, encapsulated custom HTML elements બનાવવા માટે છે — framework-agnostic અને standards-based. ત્રણ તકનીકો એકસાથે કામ કરે છે:
<template>, <slot>) — inert, reusable markup.class UserCard extends HTMLElement {
connectedCallback() { // lifecycle: runs when added to the page
const shadow = this.attachShadow({ mode: "open" }); // create shadow DOM
shadow.innerHTML = `
<style> h2 { color: blue; } </style>
<h2>${this.getAttribute("name")}</h2>
<slot></slot>
`;
}
}
customElements.define("user-card", UserCard); // name MUST contain a hyphen
<user-card name="Ann">Extra content goes in the slot</user-card>
Shadow root માં styles scoped હોય છે — page's CSS અંદર reach કરી શકતો નથી, અને component's CSS બહાર leak થતો નથી. આ global-CSS સમસ્યા natively ઉકેલે છે:
/* page CSS */ h2 { color: red; } /* does NOT affect the <h2> inside user-card */
connectedCallback() // added to DOM
disconnectedCallback() // removed from DOM (cleanup)
attributeChangedCallback(name, old, val) // an observed attribute changed
static get observedAttributes() { return ["name"]; }
Web Components તમને reusable widgets બનાવવા દે છે જે કોઈપણ framework (અથવા કોઈ નહીં) માં કામ કરે છે true style/DOM encapsulation સાથે — design systems અને micro-frontends માટે આદર્શ છે જે વિવિધ stacks ધરાવતી teams માં શેર કરવામાં આવે છે.
તે છે તે રીતે libraries જેમ કે Shoelace framework-agnostic components ship કરે છે.
Trade-offs (verbose API, SSR/styling complexity) નો અર્થ છે કે app developers ઘણીવાર હજુ પણ React/Vue પસંદ કરે છે, પણ platform primitive શક્તિશાળી અને standards-based છે.