Reputation: 689
In Blazor there are several options for executing JavaScript code:
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");
}
}
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?
Upvotes: 5
Views: 5227
Reputation: 31
I would use the first one (import during OnAfterRenderAsync) and here is my explanation:
If you write js as an extension for specific component you will get a reusable, decomposed and maintainable js modules, that can be easily covered by unit tests/refactored in future.
Percentage of unused, but loaded in browser js content will be small and more efficient. End-users should not receive bunches of js for "just in case". Sadly but blazor by itself does not use such frontend optimization and make loads a lot of "just in case" code. coverage for several js modules in comparison to blazor.server.js
No need to place a javascript link in render. It brings some benefits:
Upvotes: 3