Web Components minangka sekumpulan API asli browser kanggo ngebuo unsur HTML khusus sing bisa digunakake maneh lan kaenkapsulasi — ora gumantung framework lan berbasis standar. Telu teknologi digabung:
<template>, <slot>) — markup inert lan bisa digunakake maneh.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>
Gaya ing njerone shadow root iku scoped — CSS kaca ora bisa mlebu ing njobo, lan CSS komponen ora bisa sumpel metu. Iki ngatasi masalah CSS global kanthi alami:
/* 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 ngidini kowe ngebuo widget sing bisa digunakake maneh sing bisa gawa ing apa-apa framework (utawa ora) karo enkapsulasi gaya/DOM sing nyata — cocok kanggo sistem desain lan micro-frontend sing dienggo bareng ing antarane tim sing nggunakake stack berlainan.
Menika carane perpustakaan kaya Shoelace ngirim komponen sing ora gumantung framework.
Trade-off (API verbose, kerumitan SSR/styling) tegese pemrogram aplikasi asih seneng React/Vue, nanging primitif platform iku kuwat lan berbasis standar.