In a prerendered Blazor Web App component, why does an IJSRuntime call in OnInitializedAsync throw, and where should a trail map's first JavaScript call go?
answer
- prerender = HTML only, no browser yet
- InvalidOperationException: being statically rendered
- OnAfterRenderAsync is skipped during prerendering
- if (firstRender) guards one-time setup
- ElementReference valid only after render
basics
~20 sDuring prerendering the component runs on the server to produce HTML before any browser connection exists, so JS interop throws an InvalidOperationException. Put the first call in OnAfterRenderAsync guarded by firstRender, which runs only once the component is interactive and its elements exist.
solid answer
~40 sInteractive render modes prerender by default: the server runs `OnInitializedAsync` and renders HTML for the first response, then the component starts again interactively. In that first pass there is no circuit or WebAssembly runtime, so `IJSRuntime` throws an `InvalidOperationException` ("JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered..."); a purely static SSR component gets a similar exception on every call. `OnAfterRenderAsync` is not called during prerendering, so it is the safe place: guard one-time setup with `if (firstRender)`, because it runs after every render. It is also the first point where an `ElementReference` such as the map's container `div` refers to a real DOM element. After loading data in JavaScript, call `StateHasChanged()` if the UI must show it.
code
razor · 23 lines@rendermode InteractiveServer
@inject IJSRuntime JS
@inject TrailService Trails
<div @ref="mapElement" class="trail-map"></div>
@code {
[Parameter] public int TrailId { get; set; }
private Trail? trail;
private ElementReference mapElement;
private IJSObjectReference? module;
protected override async Task OnInitializedAsync() =>
trail = await Trails.GetAsync(TrailId); // .NET only: safe while prerendering
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender || trail is null) return;
module = await JS.InvokeAsync<IJSObjectReference>(
"import", "./Components/Trails/TrailMap.razor.js");
await module.InvokeVoidAsync("createMap", mapElement, trail.Path);
}
}go deeper
Recall that JavaScript calls belong in OnAfterRenderAsync inside an if (firstRender) block, not in OnInitializedAsync.
Explain prerendering's two passes, why only the interactive pass can call JavaScript, and why ElementReference needs a completed render.
Design components so data loads in .NET, browser work runs after first render, and StateHasChanged is called deliberately without render loops.
Weigh prerendering's faster first paint against JavaScript-dependent widgets that render empty until interactive, and choose per page.
## What prerendering does to a component In a Blazor Web App, `InteractiveServer`, `InteractiveWebAssembly` and `InteractiveAuto` **prerender by default**. For the first request the server: 1. Creates the component and runs `SetParametersAsync`, `OnInitialized{Async}` and `OnParametersSet{Async}`. 2. Renders the result to HTML and sends it with the page. 3. Discards that instance. When the Blazor script starts in the browser, the component is created again in its interactive mode and the lifecycle runs a second time, now connected to a circuit or running in WebAssembly. Only this second instance can talk to the browser. ## Why the call throws During step 1 nothing is listening in a browser yet. The JS runtime available to the prerendering component refuses the call: | Situation | Exception and message | |---|---| | Interactive Server component during prerender | `InvalidOperationException`: "JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method." | | Component with no render mode (static SSR) | `InvalidOperationException`: "JavaScript interop calls cannot be issued during server-side static rendering, because the page has not yet loaded in the browser." | | Interactive Server after the circuit is permanently gone | `JSDisconnectedException` | So `await JS.InvokeAsync<...>(...)` in `OnInitializedAsync` works in a non-prerendered app and fails as soon as prerendering is on, which is the default. ## OnAfterRenderAsync(firstRender) is the place `OnAfterRender` and `OnAfterRenderAsync` **are not called during prerendering**; they run once the component renders interactively. That gives three guarantees at once: - The browser is connected, so interop works. - The component's markup is in the DOM, so an `ElementReference` captured with `@ref` points at a real element. Before the first render it is an empty reference. - The method runs after **every** render, so `firstRender` tells you this is the first one. Initialize the trail map inside `if (firstRender)`; without the guard each re-render would create another map. ## A trail map, step by step - The markup renders an empty `<div @ref="mapElement">`. - `OnInitializedAsync` loads the trail from a service: pure .NET, safe during prerendering. - `OnAfterRenderAsync(firstRender: true)` imports the map's JavaScript module and passes it `mapElement` and the trail's coordinates. - If JavaScript returns something the UI shows, such as the trail's elevation profile, store it and call `StateHasChanged()`; a change made inside `OnAfterRenderAsync` does not trigger a render on its own. - Later updates, such as a new `Trail` parameter, go through `OnParametersSetAsync` only when the module is already loaded, or are queued for the next `OnAfterRenderAsync`. ## Where interop is safe and where it is not | Place | Safe for JS interop? | Why | |---|---|---| | Constructor, `SetParametersAsync`, `OnInitialized{Async}`, `OnParametersSet{Async}` | Not while prerendering | They run in the prerender pass on the server | | `OnAfterRender{Async}` | Yes | Skipped during prerendering; runs after the DOM exists | | Event handlers such as `@onclick` | Yes | Events are only dispatched to interactive components | | `Dispose`/`DisposeAsync` on Interactive Server | Only with a `try`/`catch` | The circuit may already be gone | The pattern generalizes: anything the browser must do waits for the first interactive render or for a user event, and anything that only needs .NET runs in initialization. ## Related traps - **Reading browser state during prerender.** Window size, `localStorage` or time zone cannot be read in `OnInitializedAsync`; read them after the first interactive render and accept that the prerendered HTML did not know them. - **Double work.** Because initialization runs twice with prerendering, a data load appears twice; persisting prerendered state avoids the second load. - **Do not detect prerendering by catching the exception.** Structure the code so interop simply happens after render; `RendererInfo.IsInteractive` can tell a component whether it is currently interactive.
- In a globally interactive app, the map works when reached by an in-app link but throws on a full browser refresh; why?A full refresh is a new HTTP request, so the page is prerendered and `OnInitializedAsync` first runs on the server without a browser connection, where JS interop throws. With interactive routing, in-app navigation happens inside the running circuit and does not prerender. Moving the interop into `OnAfterRenderAsync` with `firstRender` makes both paths work.
- Why can a value set from JavaScript inside OnAfterRenderAsync not appear on screen?`OnAfterRenderAsync` runs after the render completed, and changing a field there does not schedule another render. Call `StateHasChanged()` after storing the value. Keep it inside the `firstRender` branch or behind a check, or each render triggers another render.
- OnInitializedAsync is the right place for JS calls because it runs once.
- OnAfterRenderAsync also runs during prerendering on the server.
- An ElementReference can be passed to JavaScript in OnInitialized.
- Without a firstRender check, OnAfterRenderAsync runs only after the first render anyway.
- Disabling the exception with a try/catch is the recommended prerender fix.