Sub topic 1
The Web Component Standards LWC Builds On
Prerequisites
This chapter assumes you already have:
- Basic HTML and CSS, including selectors and the cascade.
- JavaScript fundamentals, including classes,
extends, and arrow functions. - Familiarity with the browser DOM and
addEventListener. - A general idea of what a UI component is: a reusable piece of markup, style, and behavior.
You don't need any Salesforce experience. Everything here runs in a plain browser.
Why start with standards
Lightning Web Components (LWC) is a thin framework layered on features that browsers already ship. If you know which behavior comes from the browser and which comes from LWC, you can debug faster and reuse your knowledge outside Salesforce. This chapter covers the four standards LWC relies on. Later chapters show how LWC uses each one.
| Standard | What it gives you | Main API |
|---|---|---|
| Custom elements | Your own HTML tags backed by a JavaScript class | `customElements.define()` |
| Shadow DOM | A private DOM subtree with scoped styles | `attachShadow()` |
| HTML templates and slots | Inert markup to clone, and placeholders for outside content | `<template>`, `<slot>` |
| ES modules | Files that import and export code with their own scope | `import`, `export` |
Together, the first three are called web components.
Custom elements
A custom element is a class that extends HTMLElement, registered under a tag name. The name must contain a hyphen, such as user-card. This rule keeps custom names from colliding with built-in tags.
class HelloGreeting extends HTMLElement {
connectedCallback() {
this.textContent = `Hello, ${this.getAttribute('name') ?? 'World'}!`;
}
}
customElements.define('hello-greeting', HelloGreeting);The browser calls methods on your class at defined moments. These are the custom element callbacks:
constructor()runs when the element is created.connectedCallback()runs when the element is inserted into a document.disconnectedCallback()runs when it is removed.attributeChangedCallback()runs when an attribute listed instatic observedAttributeschanges.
Attributes are always strings. Properties on the class can hold any value. This difference matters later, when LWC exposes public properties.
Shadow DOM
Shadow DOM gives an element a private subtree, called a shadow root. Markup and CSS inside it are isolated from the rest of the page.
- Selectors in the page's stylesheet can't reach into the shadow tree.
- Styles inside the shadow tree don't leak out.
document.querySelector()doesn't return nodes inside a shadow root.
Calling attachShadow({ mode: 'open' }) returns the shadow root and exposes it as element.shadowRoot. In closed mode, shadowRoot is null to outside code. Some styling still crosses the boundary: inherited properties such as color and font-family, and CSS custom properties like --brand-color.
Templates and slots
The <template> element holds markup that the browser parses but does not render, run, or load. You clone its content when you need a copy.
The <slot> element marks a place inside a shadow tree where the element's light DOM children appear. Light DOM means the children written between the custom element's tags. A slot can have fallback content, which shows when no child is supplied.
The following page uses all three features. Save it as an .html file and open it in a browser:
<!DOCTYPE html>
<html lang="en">
<body>
<template id="user-card-template">
<style>
p { color: teal; font-weight: bold; }
</style>
<p>User: <slot>Anonymous</slot></p>
</template>
<user-card>Ada</user-card>
<user-card></user-card>
<p>This paragraph is not teal.</p>
<script type="module">
const template = document.getElementById('user-card-template');
class UserCard extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: 'open' });
root.appendChild(template.content.cloneNode(true));
}
}
customElements.define('user-card', UserCard);
</script>
</body>
</html>The first card shows "User: Ada" because the text node fills the slot. The second shows "User: Anonymous" from the fallback. The final paragraph stays unstyled, because the p rule lives inside the shadow roots.
ES modules
An ES module is a JavaScript file that declares its dependencies with import and its public surface with export. Each module has its own scope, so top-level variables don't become globals. Modules are loaded in strict mode, evaluated once, and then cached.
// formatName.js
export function formatName(first, last) {
return `${last}, ${first}`;
}
export default class Person {
constructor(first, last) {
this.name = formatName(first, last);
}
}// main.js
import Person, { formatName } from './formatName.js';
console.log(formatName('Ada', 'Lovelace')); // Lovelace, Ada
console.log(new Person('Alan', 'Turing').name); // Turing, AlanA module may have one default export and any number of named exports. Default imports take any local name. Named imports must match the exported name. In browsers, relative import paths need the file extension.
How the pieces fit together
Read the diagram top to bottom. The module delivers the class. Registration ties the class to a tag. Every instance of that tag gets its own shadow root, filled from a template, with slots receiving content from the parent's markup.
Common errors
- Tag name without a hyphen.
customElements.define('card', ...)throws aSyntaxError. - Defining the same name twice. The second call throws a
NotSupportedError. Each tag name can be registered once per page. - Attaching a shadow root twice. Putting
attachShadow()inconnectedCallback()fails when the element is moved, because that callback runs again on each insertion. Create the shadow root in the constructor. - Reading attributes in the constructor. An element created by the parser may not have its attributes yet in some paths. Read them in
connectedCallback()orattributeChangedCallback(). - Expecting page CSS to style shadow content. A global
p { color: red; }has no effect inside a shadow root. Use inherited properties or CSS custom properties to pass styling in. - Querying across the boundary.
document.querySelector('p')won't find a paragraph inside a shadow root. Query through the root, for exampleelement.shadowRoot.querySelector('p'). - Forgetting
type="module". Without it,importstatements in a script cause a syntax error.
What LWC takes from each standard
This preview shows where the next chapters are going.
- An LWC component is a class that becomes a custom element. You write
extends LightningElementinstead ofextends HTMLElement. - By default, each component renders into a shadow root, so its styles are scoped.
- Each component's HTML file is a
<template>that the compiler turns into rendering code. - Every component is an ES module that imports from other modules and exports its class.
Everything else, such as @api, {expression} binding, and the for:each directive, is framework behavior. The last chapters return to that split in detail.
Exercise
You define class Badge extends HTMLElement with a shadow root containing <style>span { color: red; }</style><span>New</span>. The page also has <span>Page text</span>. Does the page's span turn red, and what does document.querySelector('span') return for a page where <span>Page text</span> appears after the badge?
Show answer
The page's span stays unchanged, because the style rule lives inside the shadow root and does not leak out. document.querySelector('span') returns the page's <span>Page text</span>, because it doesn't search inside shadow roots, even when the badge appears earlier in the document.
Exercise
Why should attachShadow() be called in the constructor rather than in connectedCallback()?
Show answer
connectedCallback() runs each time the element is inserted into a document, including after it is moved. A second attachShadow() call on the same element throws an error. The constructor runs once per element.