SvjMan
SvjMan

Reputation: 689

What is the best practice to load JS modules in Blazor client side?

In Blazor there are several options for executing JavaScript code:

  1. 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");
            }
        }
  1. 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?

Upvotes: 5

Views: 5227

Answers (1)

phatimperfection
phatimperfection

Reputation: 31

I would use the first one (import during OnAfterRenderAsync) and here is my explanation:

  1. 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.

  2. 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

  3. No need to place a javascript link in render. It brings some benefits:

Upvotes: 3

Related Questions