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 ਹੁੰਦੇ ਹਨ — ਪੰਨੇ ਦਾ CSS ਅੰਦਰ ਨਹੀਂ ਜਾ ਸਕਦਾ, ਅਤੇ component ਦਾ CSS ਬਾਹਰ ਨਹੀਂ ਲੀਕ ਹੋ ਸਕਦਾ। ਇਹ 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 ਵਿੱਚ (ਜਾਂ ਕੋਈ ਨਹੀਂ) real style/DOM encapsulation ਨਾਲ ਕੰਮ ਕਰਦੇ ਹਨ — design systems ਅਤੇ micro-frontends ਲਈ ਆਦਰਸ਼ ਜੋ ਵੱਖ-ਵੱਖ stacks ਵਰਤਣ ਵਾਲੀਆਂ ਟੀਮਾਂ ਵਿੱਚ shared ਹੁੰਦੇ ਹਨ।
ਇਹ ਤਰੀਕਾ ਹੈ ਜਿਸ ਤਰ੍ਹਾਂ Shoelace ਜਿਵੇਂ libraries framework-agnostic components ship ਕਰਦੀਆਂ ਹਨ।
Trade-offs (verbose API, SSR/styling complexity) ਦਾ ਮਤਲਬ ਹੈ ਕਿ app developers ਅਕਸਰ ਹਾਲੇ ਵੀ React/Vue ਨੂੰ ਪਸੰਦ ਕਰਦੇ ਹਨ, ਪਰ platform primitive ਸ਼ਕਤੀਸ਼ਾਲੀ ਅਤੇ standards-based ਹੈ।