JavaScript interop lets .NET code in Blazor communicate with JavaScript in the browser. A Razor component can dynamically import a JavaScript module after its first render and call its initialization function, avoiding a global script that loads on pages where it cannot work. section 5.3.3
Listing 5.5 Dynamic loading of the JavaScript file
@code {
private IJSObjectReference? _module;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) #1
{
_module =
await JS.InvokeAsync<IJSObjectReference>("import", "./js/chat.js"); #2
await _module.InvokeVoidAsync("init"); #3
}
}
}
The component imports chat.js on first render, stores the module reference, and invokes init. section 5.3.3
Interop also lets Blazor update an OpenLayers map from UI changes. For those updates, the Razor component must render in interactive mode and be fully rendered first. section 4.5
