Blazor allows JavaScript isolation in standard JavaScript modules. JavaScript isolation provides the following benefits:
- JavaScript code is allowed to load only specified components.
- Imported JavaScript does not affect any global namespace.
- Library and component consumers are not required to import the related JavaScript.
Create an export JavaScript function in the wwwroot/script folder.
[isolationScript.js]export function jsIsolation(value) {
console.log(value);
}Import the JavaScript function using the IJSRuntime.InvokeAsync method in Blazor and call the JavaScript method on button click event.
[Index.razor]
The JavaScript code file loads only during a button click event. It will not load again and again for each button click.@page "/"
@inject IJSRuntime JSRuntime
Enter text:<input @bind="content" />
<button class="btn btn-primary" @onclick="OnClickButton">Click</button>
@code {
private string content { get; set; }
private async void OnClickButton()
{
var jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./script/isolationScript.js");
await jsModule.InvokeVoidAsync("jsIsolation", content);
}
}
Refer to this documentation for more details.
Share with