Search code examples
blazor.net-6.0blazor-webassemblyrazor-components

Load JS file with custom razor component in Blazor app


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

  • Board.razor
    • In this file I have <h1>Board component</h1>
  • Board.razor.js
    • In this file I simply have a console.log('test'); statement

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" />

Solution

  • 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) {
    ...
    }