This is a proof-of-concept for how to render Blazor Components with JavaScript.
The idea is to statically render most of the HTML on the page on the server, but occasionally you need "islands of interactivity".
This is where Blazor Islands
comes in.
This is only needed for Blazor SSR (Server Side Rendering) as Blazor InteractiveWebAssembly
/InteractiveServer
already supports JavaScript interop through
the IJSRuntime
interface.
It works by adding
a BlazorIslandsFeature
Feature
to the HttpContext.Features
collection, which is then used by the BlazorIslandsMiddleware
to append <script>
tags to the end of the HTML document (... after the <html>
tag :> )
- Add the various
BlazorIslands
services to yourIServiceCollection
.- Call
builder.Services.AddBlazorIslands();
in yourProgram.cs
file.
- Call
- Add the
BlazorIslands
middleware to yourIApplicationBuilder
.- Call
app.UseBlazorIslands();
in yourProgram.cs
file.
- Call
- Add JavaScript sources to the
IJavaScriptSourceFeature
feature.- This can be done in two ways:
- By creating a Razor Component that inherits from
JavaScriptComponentBase
and overriding theJavaScriptSources
property.- This is the most idiomatic way to use
BlazorIslands
. - This will automatically add the
IBlazorIslandsFeature
to theHttpContext.Features
collection.
- This is the most idiomatic way to use
- By accessing the
IJavaScriptSourceFeature
from theHttpContext.Features
collection, and then callingAddSource(...)
on it.- This is useful for when you need to add JavaScript sources from a service or other non-component class.
- This will not automatically add the
IBlazorIslandsFeature
to theHttpContext.Features
collection, so you will need to do that manually. - Keep in mind that you need to ensure that you only add it to requests that are actually Blazor SSR requests, which I'm not sure how to do yet.
- By creating a Razor Component that inherits from
- This can be done in two ways: