liveBook · Manning

JavaScript interop

As explained in Building Distributed Applications that Work

JavaScript interop is a mechanism for communication between .NET code in Blazor and JavaScript code running in the browser.

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

How Building Distributed Applications that Work covers it

How deep it goes
Implements a first-render module import and initialization call, and specifies rendering conditions for map updates.
Examples
Uses a chat.js module initialized by a Razor component and an OpenLayers map updated from Blazor.
What it assumes
Requires interactive rendering and a fully rendered Razor component before applying map updates.
What you can do after
Apply Blazor JavaScript interop to load a JavaScript module after rendering or update an interactive map.
How it connects
Connects Blazor and JavaScript with Razor component rendering, SignalR, and OpenLayers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Distributed Applications that Work. The section links point to the parts of the book it draws on.