Autoloader

Loads any web component the first time its tag appears, morphs included.

zweiundeins <sb-autoloader> loader lazy modules custom-elements infrastructure Since 2026-09-23 MIT licence 1.0 kB0 Open in playground Edit on GitHub

Playground

loaded on demand

Put it on a page and every custom element loads itself the first time its tag shows up: on the first render, and later too, when a Datastar morph or a script adds markup. Nothing else changes, and pages ship only the components they actually use.

It is the generic version of the autoloader this site serves at /c/autoloader.js, which carries Starbase's own tag map. This one takes the map (or a URL pattern) from you, and works with any web component, not only Rocket ones.

Examples

A map of tags

loaded on demand
<sb-autoloader modules='{"demo-badge": "/c/autoloader/demo-badge.js"}'></sb-autoloader>
<demo-badge>loaded on demand</demo-badge>

demo-badge is a plain custom element with no dependencies. Nothing on the page imports it; the autoloader fetches it because the tag is there.

A pattern for a whole folder

With a naming convention, one line covers every component. {tag} is the element's name, and match keeps it to your own tags, so unrelated elements (a third-party widget, an icon element) are left alone:

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

<x-chart></x-chart>   <!-- loads /components/x-chart/x-chart.js -->
<x-table></x-table>   <!-- loads /components/x-table/x-table.js -->

Entries in modules win over the pattern, so exceptions stay easy:

<sb-autoloader
  pattern="/components/{tag}/{tag}.js"
  match="^x-"
  modules='{"x-legacy": "https://cdn.example.com/legacy/bundle.js"}'
></sb-autoloader>

No flash of undefined elements

Custom elements are empty until their module arrives. Put a class on <html>, hide undefined elements with it, and name it in cloak: it is removed once the components on the page at startup have loaded (or failed), or after timeout (3 s by default), whatever happens and even if the loader is gone by then, so a slow or failed module can never leave the page blank.

<html class="loading">
<style>.loading :not(:defined) { visibility: hidden }</style>

<sb-autoloader pattern="/c/{tag}/{tag}.js" cloak="loading"></sb-autoloader>

Watch what it loads

sb-load fires per component. sb-ready fires once, when every component that was on the page at startup has loaded or failed, however long that takes (timeout only lifts the cloak). It doesn't fire again when a morph moves the loader, and later arrivals fire sb-load only.

a tag of its own

<div data-signals="{_log: 'waiting…'}">
  <sb-autoloader
    modules='{"demo-card": "/c/autoloader/demo-badge.js?tag=demo-card"}'
    data-on:sb-load="$_log = 'loaded <' + evt.detail.tag + '>'"
    data-on:sb-ready="$_log += ' · ready (' + evt.detail.loaded + ')'"
    data-on:sb-load-error="$_log = 'could not load <' + evt.detail.tag + '>: ' + evt.detail.error"
  ></sb-autoloader>
  <demo-card>a tag of its own</demo-card>
  <p data-text="$_log"></p>
</div>

(The demo module takes the tag it defines from ?tag=, so this example loads something the examples above haven't.) A tag that is already defined is never fetched again, so an autoloader that finds nothing to do goes straight to sb-ready with loaded: 0.

From JavaScript:

  • el.ready is a promise that resolves with the number of components this loader loaded, when sb-ready fires.
  • el.load('x-chart') fetches one by hand. It returns a promise that resolves once the tag is defined and rejects when its module fails, or nothing when the tag is already defined or no module is known for it.
  • el.discover(root) loads the undefined elements in a tree the loader doesn't watch, such as a shadow root your own code filled (el.discover(this.shadowRoot)) or markup that isn't in the document yet. It returns a promise that settles when they all have (Promise.allSettled).

Dependencies between components

A component that renders another tag inside its own shadow root would otherwise only be discovered after it rendered. List those tags in requires and they load together:

<sb-autoloader
  pattern="/c/{tag}/{tag}.js"
  requires='{"sb-code-playground": ["sb-code-editor"]}'
></sb-autoloader>

Notes

  • Wrapping is optional. <sb-autoloader> works as a single tag anywhere on the page; children render untouched, so you can also wrap the markup that needs the components.
  • Once per tag. Two autoloaders on a page, or one that survives a morph, never fetch the same module twice: a loader that finds a tag another one is already loading waits for that load (its sb-ready and its cloak too), and only the loader that fetched it counts it and fires sb-load. A failed load is retried, and the module fetched again, when the tag appears again.
  • Shadow roots. It watches the document, so components inside other components' shadow roots are discovered when those render into the page, not before. requires and el.discover(root) cover the rest.
  • Datastar. sb-autoloader is itself a Rocket component: the page needs Datastar, with the import map for datastar, and loading starts once Datastar is ready. The modules it loads can be any web components; Rocket ones use that same import map.
  • A failed module reports through reportError (so window.onerror sees it) and emits sb-load-error. So does a module that loads but doesn't define its tag: a module must define it while it runs (as Rocket components and nearly all others do), not later. A match that isn't a valid regular expression is reported the same way, once per value, and the pattern is skipped.
  • demo-badge.js in this component's folder belongs to the examples above, not to the loader, so the size table doesn't count it. It is served at /c/autoloader/demo-badge.js, so in a pull-request preview (where the component is not in the catalog yet) the examples report a failed load: the loader works, the demo module is simply not there.

Styling

sb-autoloader has no box of its own (display: contents) and draws nothing, so there is nothing to style. The components it loads are styled as their own pages describe.

Accessibility

The element has no box of its own (display: contents) and no role; it adds nothing to the accessibility tree and takes no focus. Children, if you wrap any, render exactly where they are written. Use cloak so people don't see half-built elements, and remember the page must work if a module never arrives.

Installation

Add Datastar with Rocket and the Starbase autoloader once per page, then use the tag: the autoloader imports each component the first time its tag appears, including tags a Datastar morph adds later. The Datastar here is v1.0.5 with Starbase's patches. The components also run on the official v1.0.4 and v1.0.5.

<script type="importmap">
  { "imports": { "datastar": "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js" } }
</script>
<script type="module" src="https://starbase.zweiundeins.gmbh/c/autoloader.js"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

No flash of undefined elements: put class="sb-cloak" on <html> and add .sb-cloak :not(:defined) { visibility: hidden } to your CSS. The autoloader removes the class once the page's components are defined.

Load just this component, pinned to this version: all its modules in one minified file with its integrity hash, so the browser refuses it if a single byte changes.

<script type="importmap">
  {
    "imports": { "datastar": "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js" },
    "integrity": {
      "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js": "sha384-AfXVdZ/qxhMEHK4Nz/pJT6jl9xm3HGMBLBtC9yRuU5A7AQtXHYC0x6ap034vDqBV"
    }
  }
</script>
<script type="module" src="https://starbase.zweiundeins.gmbh/c/autoloader@ad9bda111796/autoloader.bundle.min.js" integrity="sha384-rvOUqwwMHMqBmRDX73x04ctY8bn6ENnLsGQJnhvWdj4XNB/J9BimPu+/Idr2AOXg"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

Or the minified module files (one file, which the browser requests as it finds their imports), each pinned in the import map:

<script type="importmap">
  {
    "imports": { "datastar": "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js" },
    "integrity": {
      "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js": "sha384-AfXVdZ/qxhMEHK4Nz/pJT6jl9xm3HGMBLBtC9yRuU5A7AQtXHYC0x6ap034vDqBV",
      "https://starbase.zweiundeins.gmbh/c/autoloader@ad9bda111796/autoloader.min.js": "sha384-+UQa9xWTnD+MTwv5mM+WEHVu9U2rkw1OSCcuvN4tDg6OqUBSb4Iz3SbhC7lfjNm6"
    }
  }
</script>
<script type="module" src="https://starbase.zweiundeins.gmbh/c/autoloader@ad9bda111796/autoloader.min.js" integrity="sha384-+UQa9xWTnD+MTwv5mM+WEHVu9U2rkw1OSCcuvN4tDg6OqUBSb4Iz3SbhC7lfjNm6"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

In production, pin today's whole catalog: its autoloader and an import map with integrity hashes, so the browser refuses any file that changed. This map covers Datastar and this component; importmap.json has the hashes of every component, to merge into yours.

<script type="importmap">
  {
    "imports": { "datastar": "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js" },
    "integrity": {
      "https://starbase.zweiundeins.gmbh/c/datastar@5f98646d7d3d/datastar-rocket.js": "sha384-AfXVdZ/qxhMEHK4Nz/pJT6jl9xm3HGMBLBtC9yRuU5A7AQtXHYC0x6ap034vDqBV",
      "https://starbase.zweiundeins.gmbh/c/autoloader@ad9bda111796/autoloader.bundle.min.js": "sha384-rvOUqwwMHMqBmRDX73x04ctY8bn6ENnLsGQJnhvWdj4XNB/J9BimPu+/Idr2AOXg"
    }
  }
</script>
<script type="module" src="https://starbase.zweiundeins.gmbh/c/@81f24b268adb/autoloader.js" integrity="sha384-bWIhsIq9SpNUiIZyG/lv190MgHA05m8BVYA3LyIoE/pgOF3NUt0437e++4Ht1NcS"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

Components import only datastar and their own files, so copying is enough: save each component's one file (and a file it loads on first use, keeping its folder), and point the import map at your own copy of datastar-rocket.js (the /js/ paths stand for yours).

  • <sb-autoloader>
    • autoloader.bundle.min.js one file 1.0 kB brotli
<script type="importmap">
  { "imports": { "datastar": "/js/datastar-rocket.js" } }
</script>
<script type="module" src="/js/autoloader/autoloader.bundle.min.js"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

Or copy the module files, keeping each component's folder, and load each component's module:

  • <sb-autoloader>
<script type="importmap">
  { "imports": { "datastar": "/js/datastar-rocket.js" } }
</script>
<script type="module" src="/js/autoloader/autoloader.min.js"></script>

<sb-autoloader pattern="/components/{tag}/{tag}.js" match="^x-"></sb-autoloader>

In Go, render it with its typed templ wrapper: one field per prop, generated from the component's manifest (the module's README has the type rules). Add the module:

go get github.com/zweiundeins/starbase/templ@latest

Then load it, pinned with integrity hashes to the versions the module was generated with, and use it:

// In <head>: the components you list, pinned,
@sb.Imports(sb.ImportsProps{Components: []sb.Tag{sb.TagAutoloader}})
// or the autoloader, which also loads tags a morph adds later: @sb.Imports(sb.ImportsProps{})
// or, around the content of <body>, the components it renders: @sb.Tracked(sb.ImportsProps{}) { … }

@sb.Autoloader(sb.AutoloaderProps{Pattern: "/components/{tag}/{tag}.js", Match: "^x-"})

Size

A page loads this component as one file, its bundle, compressed the way it is served (gzip -9, brotli -11): brotli is what it downloads. Datastar and Rocket are shared by every component and not counted.

FileOriginalgzipbrotli
autoloader.bundle.min.js 2.1 kB1.2 kB1.0 kB
As module files: one request, 966 B minified with brotli

For a page that loads the module files as they are, requesting each one as it finds its import, or bundles them itself. Each file compressed on its own; the minified one is what the page downloads, and the readable source is always there too.

FileOriginalgzipbrotliminified
autoloader.js 6.4 kB2.7 kB2.3 kB966 B

API reference

Props

AttributeTypeDefaultDescription
modulesjson{}Explicit map of tag to module URL: {"x-chart": "/js/x-chart.js"}. Wins over pattern.
patternstring""URL template for tags not in modules, with {tag}, e.g. "/components/{tag}/{tag}.js".
matchstring""Regular expression the tag must match before pattern applies, e.g. "^x-". Empty: every unknown custom element.
requiresjson{}Tags a component renders itself, loaded with it: {"x-table": ["x-cell"]}.
basestring""Base for relative URLs. Default: the document's base URL.
cloakstring""Class removed from <html> once the components present at startup have loaded or failed, or after timeout (against the flash of undefined elements).
timeoutnumber3000Remove the cloak class after this many ms, whatever happens (sb-ready still waits for the loads).

Slots

NameDescription
defaultOptional markup to wrap; it renders exactly as written.

Events

NameDescription
sb-loadAfter a component is defined. detail: { tag, url }.
sb-load-errorWhen a module fails to load, or loads without defining its tag. detail: { tag, url, error }.
sb-readyOnce, when every component present at startup has loaded or failed (right away when there were none). detail: { loaded }.