Library for script and css injection to Blazor pages
dotnet add package Sitko.Blazor.ScriptInjector
Register in DI and configure in Startup.cs
services.AddScriptInjector(Configuration);
Inject IScriptInjector
@inject IScriptInjector _scriptInjector
await _scriptInjector.InjectAsync(ScriptInjectRequest.Inline("inline", "console.log('Inline script is executed');"));
await _scriptInjector.InjectAsync(ScriptInjectRequest.FromUrl("url", "/script.js"));
Embed script as resource in your .csproj
<ItemGroup>
<EmbeddedResource Include="assembly.js" LogicalName="assembly.js" />
</ItemGroup>
Then inject
await _scriptInjector.InjectAsync(ScriptInjectRequest.FromResource("resource", GetType().Assembly, "assembly.js"));
await _scriptInjector.InjectAsync(CssInjectRequest.Inline("inlinecss", "body{background: blue;}"));
await _scriptInjector.InjectAsync(CssInjectRequest.FromUrl("urlcss", "/style.css"));
Embed script as resource in your .csproj
<ItemGroup>
<EmbeddedResource Include="assembly.css" LogicalName="assembly.css" />
</ItemGroup>
Then inject
await _scriptInjector.InjectAsync(CssInjectRequest.FromResource("resourcecss", GetType().Assembly, "assembly.css"));
Pass callback to InjectAsync
. For example - chain script load:
private Task LoadInlineScriptAsync()
{
return _scriptInjector.InjectAsync(ScriptInjectRequest.Inline("inline", "console.log('Inline script is executed');"), LoadUrlScriptAsync);
}
private Task LoadUrlScriptAsync(CancellationToken cancellationToken)
{
return _scriptInjector.InjectAsync(ScriptInjectRequest.FromUrl("url", "/script.js"), LoadResourceScriptAsync, cancellationToken);
}
private Task LoadResourceScriptAsync(CancellationToken cancellationToken)
{
return _scriptInjector.InjectAsync(ScriptInjectRequest.FromResource("resource", GetType().Assembly, "assembly.js"), _ =>
{
// all scripts are loaded
return Task.CompletedTask;
}, cancellationToken);
}
});
await _scriptInjector.InjectAsync(new[]
{
ScriptInjectRequest.Inline("inline", "console.log('Inline script is executed');")
ScriptInjectRequest.FromUrl("url", "/script.js"),
ScriptInjectRequest.FromResource("resource", GetType().Assembly, "assembly.js"),
CssInjectRequest.Inline("inlinecss", "body{background: blue;}"),
CssInjectRequest.FromResource("resourcecss", GetType().Assembly, "assembly.css"),
CssInjectRequest.FromUrl("urlcss", "/style.css")
}, _ =>
{
// all scripts are loaded
return Task.CompletedTask;
});
All script requests with same id will be executed only once per scope
await _scriptInjector.InjectAsync(new[]
{
_scriptInjector.Inline("inline", "console.log('Inline script is executed');"),
_scriptInjector.Inline("inline", "console.log('Inline script 2 is executed');"),
_scriptInjector.Inline("inline", "console.log('Inline script 3 is executed');"),
});
In browser console will be only
Inline script is executed
- Clone repo
- Go to
apps/Sitko.Blazor.ScriptInjector.Demo
- Run
dotnet run
- Open https://localhost:5001/ in browser