In Blazor there are several options for executing JavaScript code:
- Load a js file into the instance of IJSObjectReference and call InvokeAsync on it:
Blazor component's code behind file:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
IJSObjectReference module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", ".script1.js");
await module.InvokeVoidAsync("sampleFunction1");
}
}
- Add a js file as a script to HTML markup and call InvokeAsync on IJSRuntime instance:
index.html:
<script src="script1.js"></script>
Blazor component's code behind file:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("sampleFunction1");
}
}
Both approaches work, but which one is preferred from the perspective of performance, code maintenance and code cleanliness?