The ResourceLoader class is designed to manage the loading and initialization of scripts, styles, and JavaScript modules in a Blazor application. It provides methods to asynchronously load scripts and styles, wait for variables to be available, and manage the lifecycle of JavaScript modules.
It ensures that each resource is only loaded once (through this interop), even with multiple concurrent calls.
dotnet add package Soenneker.Blazor.Utils.ResourceLoader
To load a script, use the LoadScript method. It injects the file into the DOM.
await resourceLoader.LoadScript("https://example.com/script.js");LoadScriptAndWaitForVariable is also available as a legacy fallback for third-party scripts that expose globals instead of ES module exports:
await resourceLoader.LoadScriptAndWaitForVariable("https://example.com/script.js", "variableName");To load an ES module script tag, use LoadModuleScript:
await resourceLoader.LoadModuleScript("https://example.com/module.js");If that module assigns a global and you need to wait for it, use:
await resourceLoader.LoadModuleScriptAndWaitForVariable("https://example.com/module.js", "myGlobal");To load a style, use the LoadStyle method. It injects the file into the DOM.
await resourceLoader.LoadStyle("https://example.com/style.css");To import a JavaScript module, use the ImportModule method:
var module = await resourceLoader.ImportModule("moduleName");ImportModule already waits for the ES module import to complete, so Soenneker-owned interops should import the module directly and invoke its exports.
To import an external ES module by absolute URI, use ImportExternalModule:
var module = await resourceLoader.ImportExternalModule("https://cdn.jsdelivr.net/npm/some-package/+esm");This is useful for ESM-first libraries that do not expose browser globals.
To wait for a JavaScript global to be available, use the WaitForVariable method:
await resourceLoader.WaitForVariable("variableName");Be sure to dispose of a module after you're done interacting with it. To dispose of a JavaScript module, use the DisposeModule method:
await resourceLoader.DisposeModule("moduleName");External modules imported by URL can also be disposed:
await resourceLoader.DisposeExternalModule("https://cdn.jsdelivr.net/npm/some-package/+esm");