In a previous post I explained how to use CSS isolation in a Blazor component to ensure the style of a component is not impacted by the global style or other components. JS isolation is similar but for JavaScript code. It allows to load JavaScript code for a specific component. One of the goal of JS isolation is to make reusable component that are not impacted by the global scope. In the previous version of Blazor, you needed to expose JS function in the global scope (window) and to add the <script> element manually. JS isolation fixes both issues!

JS isolation is based on standard ES modules. ES modules can be loaded on-demand using import("path") and the functions they expose are not accessible from the global scope. This is a game changer when creating reusable components as consumers of your library and components no longer need to manually import the related JavaScript!

In .NET, you can use ES modules using the IJSRuntime and JSObjectReferenceIJSRuntime.InvokeAsync allows to call the [import]( function and JSObjectReference allows to keep a reference to the loaded ES module.

// Load the module and keep a reference to it
// You need to use .AsTask() to convert the ValueTask to Task as it may be awaited multiple times
private Task<JSObjectReference> _module;
private Task<JSObjectReference> Module => _module ??= JSRuntime.InvokeAsync<JSObjectReference>("import", "./js/demo.js").AsTask();

#blazor core #web #javascript

JavaScript Isolation in Blazor Components
23.15 GEEK