Web Components native browser APIs کا ایک سیٹ ہے جو reusable، encapsulated custom HTML elements بنانے کے لیے ہے — framework-agnostic اور standards-based۔ تین technologies کو ملایا جاتا ہے:
Web Components native browser APIs کا ایک سیٹ ہے جو reusable، encapsulated custom HTML elements بنانے کے لیے ہے — framework-agnostic اور standards-based۔ تین technologies کو ملایا جاتا ہے:
<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 باہر نہیں نکل سکتا۔ یہ native طریقے سے global-CSS مسئلہ حل کرتا ہے:
/* 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 استعمال کرنے والی teams میں شیئر ہوں۔
یہ وہی طریقہ ہے جس سے Shoelace جیسی libraries framework-agnostic components فراہم کرتی ہیں۔
Trade-offs (verbose API، SSR/styling complexity) کا مطلب یہ ہے کہ app developers اب بھی اکثر React/Vue کو prefer کرتے ہیں، لیکن یہ platform primitive طاقتور اور standards-based ہے۔