Nestor
Nestor

Reputation: 8384

How to load a JavaScript file in the Blazor client index.html

I have the following JavaScript code in a .js file:

export function testAlert() {
  alert('Testing Blazor');
}

When I added this to my Razor component, I get a warning:

enter image description here

I added the following to the index.html file - as recommended:

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>BlazorTest</title>
  <base href="/" />
  <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
  <link href="css/app.css" rel="stylesheet" />
  <link href="BlazorTest.styles.css" rel="stylesheet" />
  <script type="text/javascript" src="scripts/testing.js"></script>
</head>

Modified the component accordingly:

@inject IJSRuntime JS

protected override async Task OnAfterRenderAsync(bool firstRender)
{
  base.OnAfterRenderAsync(firstRender);
  await JS.InvokeAsync<string>("testAlert");
}

When I load the page, I get the following error:

Unhandled exception rendering component: Could not find 'testAlert' ('testAlert' was undefined).

I checked the source of the page, and it looked like this:

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>BlazorTest</title>
  <base href="/" />
  <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
  <link href="css/app.css" rel="stylesheet" />
  <link href="BlazorTest.styles.css" rel="stylesheet" />
</head>

What happened to the modified index.html with the loaded script?

Upvotes: 0

Views: 2686

Answers (1)

Eric King
Eric King

Reputation: 11734

Sometimes the index.html file is cached by the browser. That may be the case here.

Usually forcing a refresh with Ctrl-F5 will force a download of the newly edited file.

Upvotes: 2

Related Questions