In a Blazor Web App, how do you load a collocated JavaScript module as an IJSObjectReference, and dispose it safely when the trail map component is removed?
answer
- InvokeAsync<IJSObjectReference>("import", path)
- TrailMap.razor.js beside TrailMap.razor
- @implements IAsyncDisposable
- catch JSDisconnectedException in DisposeAsync
- leave the library's element empty in Razor
basics
~10 sCall JS.InvokeAsync<IJSObjectReference>("import", "./Components/Trails/TrailMap.razor.js") after first render and invoke the module's exports. Implement IAsyncDisposable: tell the module to tear down the map, then DisposeAsync the reference, catching JSDisconnectedException when the circuit is gone.
solid answer
~40 sA file named `TrailMap.razor.js` beside `TrailMap.razor` is a collocated module published as a static asset; `await JS.InvokeAsync<IJSObjectReference>("import", "./Components/Trails/TrailMap.razor.js")` loads it with the browser's dynamic `import()` and hands back a reference whose `InvokeAsync`/`InvokeVoidAsync` call its exports, so nothing touches `window`. The reference pins the module object in a map on the JavaScript side until disposed. The component should `@implements IAsyncDisposable` and, in `DisposeAsync`, first call the module's own teardown (removing map listeners) and then `await module.DisposeAsync()`. On Interactive Server, a circuit that is already gone makes those calls throw `JSDisconnectedException`; catch it, since the browser state went with the page. Render the map's container as an empty element so Blazor's diff never fights the library's DOM.
code
razor · 26 lines@implements IAsyncDisposable
@inject IJSRuntime JS
<div @ref="mapElement" class="trail-map"></div>
@code {
[Parameter, EditorRequired] public Trail Trail { get; set; } = default!;
private ElementReference mapElement;
private IJSObjectReference? module;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
module = await JS.InvokeAsync<IJSObjectReference>("import", "./Components/Trails/TrailMap.razor.js");
await module.InvokeVoidAsync("createMap", mapElement, Trail.Path);
}
public async ValueTask DisposeAsync()
{
try
{
if (module is not null)
{
await module.InvokeVoidAsync("disposeMap", mapElement);
await module.DisposeAsync();
}
}
catch (JSDisconnectedException) { } // circuit gone: the browser state went with it
}
}go deeper
Recall the import call that returns an IJSObjectReference and that the component must dispose it in DisposeAsync.
Explain JavaScript isolation, collocated .razor.js paths, the empty-element pattern and the disposal order.
Handle JSDisconnectedException on Interactive Server, release DotNetObjectReferences, and use a MutationObserver when browser cleanup must not depend on the circuit.
Set conventions for wrapping third-party JavaScript widgets so ownership of the DOM and of cleanup is unambiguous across teams.
## Why modules instead of global functions `IJSRuntime.InvokeAsync("someFunction")` looks the function up on `window`, so every script must publish globals and the page has to load them up front. **JavaScript isolation** with standard ES modules fixes both: - The module's exports stay private to the module; nothing pollutes the global namespace. - A component loads its own script when it first needs it; consumers of a component or library do not add `<script>` tags. - A module is loaded once per page even if many components import it. ## Loading a collocated module A **collocated** file sits next to the component with the `.razor.js` suffix, for example `Components/Trails/TrailMap.razor.js` for `TrailMap.razor`. The build publishes it as a static web asset at a path that mirrors the project folder. Loading it is one interop call to the browser's dynamic `import()`: 1. In `OnAfterRenderAsync` with `firstRender`, call `JS.InvokeAsync<IJSObjectReference>("import", "./Components/Trails/TrailMap.razor.js")`. 2. Keep the returned **`IJSObjectReference`** in a field. 3. Call exports through it: `module.InvokeVoidAsync("createMap", mapElement, trail.Path)`. A module in a Razor class library is addressed through its static web asset path, `./_content/{PACKAGE ID}/...`. ## Letting the mapping library own its DOM Blazor updates the page by diffing its render tree against the DOM it produced. A mapping library adds tiles, canvases and markers of its own. The safe pattern is to render an **empty element** for the library, `<div @ref="mapElement"></div>`, and never render children inside it from Razor. Blazor sees an element that is always empty and leaves its contents alone; the library owns everything inside. When the component is removed, Blazor removes that element and its whole subtree. ## Disposal, in order An `IJSObjectReference` is an entry in a map on the JavaScript side keyed by an id. Until it is disposed, the module object and whatever it holds stay reachable. A component that creates references must release them: 1. Implement `IAsyncDisposable` (`@implements IAsyncDisposable`), because releasing involves an interop call. 2. Call the module's teardown export, for example `disposeMap`, so the library removes its event listeners, timers and observers. 3. `await module.DisposeAsync()` to drop the reference. 4. Dispose any `DotNetObjectReference` you passed to the module. On **Interactive Server**, disposal often happens because the circuit ended: the user closed the tab or the network dropped. Interop calls then throw `JSDisconnectedException` ("the circuit has disconnected and is being disposed"). There is nothing left to clean in the browser, so the documented pattern is to catch and ignore it, or log at a low level. On **WebAssembly** there is no circuit to lose, and the `try`/`catch` is unnecessary. ## What to release, and how | Resource | Release with | Failure if forgotten | |---|---|---| | `IJSObjectReference` for the module | `await module.DisposeAsync()` | The module object stays pinned in the JavaScript-side reference map | | Library state (listeners, timers, observers) | The module's own teardown export | Handlers keep firing into a removed component | | `DotNetObjectReference` passed to JavaScript | `Dispose()` in .NET or `dispose()` in JavaScript | The .NET component stays reachable and leaks | | Interop calls after the circuit ended | Catch `JSDisconnectedException` | Noise in logs; no real leak | Dispose the JavaScript-side state before the .NET references it calls back into, so that a late event cannot call a disposed object. ## When cleanup must run in the browser regardless If JavaScript state must be cleaned even when the circuit is already gone, .NET cannot do it. The documented approach is a `MutationObserver` in the module that watches for the map's element being removed from the DOM and tears down the library itself. ## Common mistakes - Importing the module in `OnInitializedAsync`, which fails during prerendering. - Importing on every render instead of once behind `firstRender`. - Implementing only `IDisposable` and blocking on the async dispose call. - Rendering markup inside the library's container and getting diff errors or vanished markers. - Letting `JSDisconnectedException` escape disposal and fill logs with noise.
- Users on Interactive Server close the tab and the logs fill with JSDisconnectedException from the trail map; is this a bug, and what do you change?It is expected: the circuit ends, Blazor disposes the component, and the interop calls in `DisposeAsync` can no longer reach the browser. The browser-side map vanished with the tab, so catch `JSDisconnectedException` around the module calls and `DisposeAsync`, as the documentation recommends, and log nothing or a debug line.
- Why render the map container as an empty element instead of letting Razor render the marker list inside it?Blazor applies diffs to the DOM it believes it produced. If the library also inserts nodes there, the two disagree and updates fail or wipe the library's content. An element that is always empty in Razor is never diffed internally, so the library can own its contents until Blazor removes the element.
A hired guide for one hike: you engage the guide when the hike starts, hand back the radio when it ends, and if the guide has already left the trailhead there is nobody to return it to, so you stop trying.
- A module imported with "import" is released automatically when the component is removed.
- JSDisconnectedException during disposal means the component leaked the circuit.
- Collocated .razor.js files are bundled into blazor.web.js automatically.
- Blazor can safely render child markup inside an element a JavaScript library manages.
- Implementing IDisposable and calling DisposeAsync().AsTask().Wait() is fine for interop cleanup.