โšก Loading components

Two ways to bind classes to elements (dynamic imports or an explicit registry) plus everything around them: options, several components per element, DOM changes and errors.

Async mode

The dispatcher resolves COMPONENTS/Greeting with a dynamic import(): webpack ships it as its own chunk, fetched only when the element exists.

<div data-component="Greeting"></div>
const dispatcher = new ComponentDispatcher();
await dispatcher.importAsyncComponents();

Sync mode with a custom selector

A second dispatcher uses an explicit registry and its own attribute. No dynamic import, so it works with any bundler.

<span data-sync-component="Clock"></span>
const dispatcher = new ComponentDispatcher();
dispatcher.Selector = '[data-sync-component]';
await dispatcher.importComponents({ Clock });

Scan only a subtree

Pass a target to set up components inside one element only, for example after injecting HTML you fetched. Elements already set up are skipped.

box.innerHTML = '<span data-sync-component="Clock"></span>'.repeat(2);
await dispatcher.importComponents({ Clock }, box);

Several components, options from data attributes

Counter reads its start value and step from data-option-*; Highlight decorates the same element.

<div data-component="Counter, Highlight"
     data-option-start="10" data-option-step="5"></div>

Observing DOM changes

With observeDomChanges() new elements are mounted automatically and removed ones get _destroy(). Watch the log.

const stopObserving = dispatcher.observeDomChanges();

Error overlay

A component that throws does not break the others. In development builds it is replaced by an overlay with the stack trace.