正如 cmets 中所讨论的,Blazor 是一个 SPA,因此任何加载的脚本都可以在 Blazor 页面上使用,因为它是同一个页面。
但是,您必须在_Host.cshtml 中将它们全部列出,实际上您可能只想在需要时加载特定脚本(例如,并非所有用户都使用特定页面/需要脚本的组件)。
可以使用 JS Interop 动态加载脚本。我创建了以下scriptLoader.js 库并将其包含在_Host.cshtml 中:
// loadScript: returns a promise that completes when the script loads
window.loadScript = function (scriptPath) {
// check list - if already loaded we can ignore
if (loaded[scriptPath]) {
console.log(scriptPath + " already loaded");
// return 'empty' promise
return new this.Promise(function (resolve, reject) {
resolve();
});
}
return new Promise(function (resolve, reject) {
// create JS library script element
var script = document.createElement("script");
script.src = scriptPath;
script.type = "text/javascript";
console.log(scriptPath + " created");
// flag as loading/loaded
loaded[scriptPath] = true;
// if the script returns okay, return resolve
script.onload = function () {
console.log(scriptPath + " loaded ok");
resolve(scriptPath);
};
// if it fails, return reject
script.onerror = function () {
console.log(scriptPath + " load failed");
reject(scriptPath);
}
// scripts will load at end of body
document["body"].appendChild(script);
});
}
// store list of what scripts we've loaded
loaded = [];
这将创建一个script 元素并附加到文档的body 元素。它返回一个承诺,因为脚本将异步加载,因此您需要在 C# 代码中使用await。
loaded 数组用于避免再次重新加载脚本。任何脚本一旦加载,就会保持加载状态,除非用户刷新页面。所以负载只发生一次。
在我需要确保加载库的页面/组件上,我需要注入 IJSruntime...
@inject IJSRuntime jsRuntime
然后调用它..
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// invoke script loader
Console.WriteLine("Loading jQuery");
await jsRuntime.InvokeVoidAsync("loadScript", "https://code.jquery.com/jquery-3.4.1.js");
await jsRuntime.InvokeVoidAsync("loadScript", "myJQueryTest.js");
Console.WriteLine("Invoking jQuery");
await jsRuntime.InvokeVoidAsync("setH1", "Hello world!");
Console.WriteLine("Invoked JQuery");
await base.OnAfterRenderAsync(firstRender);
}
myJQueryTest.js 很简单:
window.setH1 = function (message) {
$('h1').text(message);
}
已创建演示代码库:https://github.com/conficient/BlazorDynamicScriptLoad