正如评论中所讨论的,Blazor 是一个 SPA,因此任何加载的脚本都可以在 Blazor 页面上使用,因为它们是同一页面。
然而,你不have将它们全部列出来_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
文档的元素。它返回一个承诺,因为脚本将异步加载,所以你需要await
在 C# 代码中。
The 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);
}
The myJQueryTest.js
很简单:
window.setH1 = function (message) {
$('h1').text(message);
}
创建演示存储库:https://github.com/conficient/BlazorDynamicScriptLoad https://github.com/conficient/BlazorDynamicScriptLoad