Skip to content

Latest commit

 

History

History
92 lines (76 loc) · 2.43 KB

index.md

File metadata and controls

92 lines (76 loc) · 2.43 KB
layout css
main.html
index.css

Web Components

The native way to build powerful user interfaces

Learn Tutorials

{% icon "package-open" %}Built in

Web Components are built right into the browser and require no additional frameworks or JavaScript libraries to pull in. Bundle sizes will be small and loading times short.

{% icon "layout-dashboard" %}Practical

Web Components are standard JavaScript, and so work anywhere that HTML does. If you're already using a framework, then Web Components will fit right in!

{% icon "zap" %}Powerful

Web Components provide new ways of building UI, like the ShadowDOM, which enables powerful new patterns for encapsulation.

{% demo %}

// Create a new stylesheet that can be shared by all `stop-watch` elements
const styles = new CSSStyleSheet()
styles.replaceSync(`
  :host {
    font-size: var(--font-size-3);
    font-style: italic;
  }
`)

// Define the StopWatch element Class
class StopWatchElement extends HTMLElement {
  static define(tag = "stop-watch") {
    customElements.define(tag, this)
  }

  // Give this element its own encapsulated DOM
  shadowRoot = this.attachShadow({ mode: "open" })

  // Initialize private state
  #start = Date.now()

  connectedCallback() {
    // Add the shared styles
    this.shadowRoot.adoptedStyleSheets = [styles]

    // Start the timer
    this.#tick()
  }

  #tick() {
    const milliseconds = Date.now() - this.#start
    const minutes = String(Math.floor(milliseconds / (1000 * 60))).padStart(2, "0")
    const seconds = String(Math.floor((milliseconds / 1000) % 60)).padStart(2, "0")
    const hundredths = String(Math.floor((milliseconds % 1000) / 10)).padStart(2, "0")

    this.shadowRoot.replaceChildren(`${minutes}:${seconds}:${hundredths}`)

    // Schedule next update
    requestAnimationFrame(() => this.#tick())
  }
}

// Register the element with the Custom Element Registry
StopWatchElement.define()
<stop-watch role="timer"></stop-watch>

{% enddemo %}