Vivendi
Vivendi

Reputation: 20997

Load JS file with custom razor component in Blazor app

In my project I have a Components folder with two files:

In the Index.razor file I load my custom component:

<Board></Board>

When I run my application I see that my Board component loads successfully.

To my understanding the .js file should be automatically discovered and loaded by the Blazor application.

So my expectation is that I should also see a console.log message in the browsers console window. But this does not happen. It seems like my JS file is not loaded?

According to this github conversation support for this should be there: https://github.com/dotnet/sdk/pull/19270

Is there something I'm missing? Or is my expectation wrong?


Additional project info

I'm running a client side Blazor app on .NET 6.0, and I have the latest packages installed in my application:

<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.7" PrivateAssets="all" />

Upvotes: 3

Views: 3202

Answers (1)

cycaHuH
cycaHuH

Reputation: 3460

While it seems to be applicable to component level .css files it doesn't work for .js. You have to load those files explicitly -> https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-6.0#load-a-script-from-an-external-javascript-file-js-collocated-with-a-component

Below is an example that I have recently used.

In Component

  1. Have a couple of variables

     [Inject]
     private IJSRuntime JS { get; set; } = default!;
     private IJSObjectReference? _jsModule;
    
  2. Overload OnAfterRenderAsync method

     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
         _jsModule ??= await JS.InvokeAsync<IJSObjectReference>(
             "import", "./Pages/Board.razor.js");
    
         await _jsModule.InvokeVoidAsync("loadBoardJS", parameters);
    
         await base.OnAfterRenderAsync(firstRender);
     }
    

Update your Board.razor.js file a little

export function loadBoardJS(parameters) {
...
}

Upvotes: 7

Related Questions