skip to content

In a Blazor Web App, what is a JavaScript initializer module, and which of its exported functions run before and after Blazor starts?

level: middleimportance: nice to knowfreq 16%

answer

  1. {ASSEMBLY NAME}.lib.module.js in wwwroot
  2. beforeWebStart(options) / afterWebStarted(blazor)
  3. per-runtime: beforeServerStart, afterWebAssemblyStarted
  4. legacy beforeStart / afterStarted skipped
  5. enableClassicInitializers

basics

~20 s

A JS initializer is a module named {ASSEMBLY NAME}.lib.module.js in wwwroot that Blazor imports at startup. In a Blazor Web App it may export beforeWebStart and afterWebStarted, plus per-runtime hooks such as beforeServerStart or afterWebAssemblyStarted.

solid answer

~40 s

Blazor discovers a module named after the app assembly, or a Razor class library's package id, with the `.lib.module.js` suffix in its `wwwroot`, and imports it while starting. In a Blazor Web App the exports it calls are `beforeWebStart(options)` before startup, `afterWebStarted(blazor)` after all `beforeWebStart` promises resolve, and runtime-specific pairs: `beforeServerStart(options, extensions)`/`afterServerStarted(blazor)` for the first Interactive Server runtime and `beforeWebAssemblyStart(options, extensions)`/`afterWebAssemblyStarted(blazor)` for WebAssembly. The older `beforeStart`/`afterStarted` exports are not invoked in a Blazor Web App unless `enableClassicInitializers` is set. Use initializers for startup work no single component owns: registering custom event types, adding scripts, configuring the circuit or boot options, or a library's setup without asking consumers to add markup.

code

javascript · 12 lines
javascript
// wwwroot/HikingTrails.lib.module.js
export function beforeWebStart(options) {
  const script = document.createElement('script');
  script.src = 'lib/trail-map/trail-map.js';
  document.head.appendChild(script);
}

export function afterWebStarted(blazor) {
  blazor.registerCustomEventType('trailpinned', {
    createEventArgs: event => ({ trailId: event.detail.trailId })
  });
}

go deeper

for a junior

Recall the {ASSEMBLY NAME}.lib.module.js name in wwwroot and that Blazor imports it at startup.

for a middle

Explain the beforeWebStart/afterWebStarted pair, the per-runtime hooks, and why legacy beforeStart is skipped in a Blazor Web App.

for a senior

Choose initializers only for app-wide startup work such as custom events or circuit options, keeping per-component setup in collocated modules.

for a principal

Govern startup scripts across libraries so initializers do not quietly slow the first interactive render on every page.

## What a JS initializer is Most Blazor JavaScript runs because a component asked for it. Some work has to happen **before or around Blazor's own startup**, before any component exists: configuring the SignalR connection, registering a custom DOM event that components bind to, or loading a library's scripts. A **JavaScript initializer** is a module Blazor imports automatically for that purpose. - **Name:** `{ASSEMBLY NAME}.lib.module.js` for the app, for example `HikingTrails.lib.module.js`, or `{PACKAGE ID}.lib.module.js` for a Razor class library. - **Location:** the project's `wwwroot` folder. - **Discovery:** the framework finds the module by that naming convention and the Blazor script imports it at startup; nothing is added to the page markup. That last point is why libraries use them: a component library can wire its startup code without telling every consumer to add a `<script>` tag. ## The Blazor Web App hooks | Export | Called | Receives | |---|---|---| | `beforeWebStart(options)` | Before the Blazor Web App starts | Blazor Web options | | `afterWebStarted(blazor)` | After all `beforeWebStart` promises resolve | The `Blazor` instance | | `beforeServerStart(options, extensions)` | Before the first Interactive Server runtime starts | Circuit start options and publish-time extensions | | `afterServerStarted(blazor)` | After the first Interactive Server runtime starts | The `Blazor` instance | | `beforeWebAssemblyStart(options, extensions)` | Before the Interactive WebAssembly runtime starts | Blazor options and extensions | | `afterWebAssemblyStarted(blazor)` | After the WebAssembly runtime starts | The `Blazor` instance | The runtime-specific hooks matter because a Blazor Web App may start the server runtime, the WebAssembly runtime, both, or neither, depending on which render modes the visited pages use. A page that is pure static SSR starts no interactive runtime at all. ## Legacy initializers Standalone Blazor WebAssembly and older Blazor Server apps use `beforeStart(options, extensions)` and `afterStarted(blazor)`. In a Blazor Web App those are **not invoked by default**. Setting the `enableClassicInitializers` start option turns them back on, but the documentation calls their execution unpredictable there; port the module to the `Web`-named hooks instead. ## Typical uses 1. Register a custom event type with `blazor.registerCustomEventType` in `afterWebStarted`; together with an `[EventHandler]` attribute in C#, components can then bind an `@ontrailpinned` event. 2. Append a third-party script in `beforeWebStart` so it is present before components need it. This guarantees the script element is added, not that the script's own asynchronous setup has finished. 3. Adjust the circuit start options in `beforeServerStart` before the first Interactive Server connection opens. 4. Ship startup behaviour from a Razor class library, for example a mapping component library that loads its stylesheet and script. ## Initializers in a Razor class library A component library is where initializers earn their keep. A hiking-maps library packaged as `Trails.Maps` can ship `wwwroot/Trails.Maps.lib.module.js`: - Its `beforeWebStart` adds the library's stylesheet and script, so an app that references the package needs no markup changes. - Its `afterWebStarted` registers the custom events its components raise. - Because the file is named after the package id, several libraries can each ship one without colliding; Blazor runs all of them. - The app can still have its own `{ASSEMBLY NAME}.lib.module.js`; both run. Keep each hook fast and idempotent. Every page that starts Blazor pays for the work, and an exception in a hook surfaces during startup for every user. ## What does not belong there - Per-component setup such as creating a map in a specific element: that belongs in the component's own module after its first render. - Anything that needs component state or a `DotNetObjectReference`, which do not exist yet when the hooks run. - Heavy synchronous work that delays the first interactive render for every page.

  • A library's initializer exports beforeStart and afterStarted and worked in a standalone WebAssembly app, but nothing runs in a Blazor Web App; why?
    A Blazor Web App calls the Web-named hooks (`beforeWebStart`, `afterWebStarted` and the per-runtime ones) and skips the legacy `beforeStart`/`afterStarted` by default. Export the new names, or, as a stopgap, set `enableClassicInitializers`, which the documentation warns runs them unpredictably.
  • On a statically rendered page of a Blazor Web App, does afterServerStarted run?
    No. It runs after the first Interactive Server runtime starts, and a page with only static SSR content starts none. `beforeWebStart` and `afterWebStarted` still run because the Blazor script starts on every page; startup code that must run everywhere belongs in those.

  • A JS initializer must be referenced with a script tag in App.razor.
  • beforeStart and afterStarted are the hooks a Blazor Web App calls.
  • afterServerStarted runs on every page, including static SSR pages.
  • beforeWebStart waits for the appended script's own asynchronous setup to finish.
  • A component's map setup belongs in the app's initializer module.