Lifecycle Considerations of JavaScript Interop
Learn how JavaScript interop in Blazor is affected by application lifecycle events.
When using JavaScript interop in Blazor, we need to be mindful of the Razor component lifecycle. There is nothing that stops us from invoking JavaScript functions from any lifecycle method. The invocation will still work and the function will still be triggered. However, there are some things that will behave differently depending on which lifecycle event the logic is triggered from. For example, as the following figure demonstrates, manipulation of DOM components will not work until after the Razor component has been rendered:
In this lesson, we will see how JavaScript interop works with the different lifecycle events. We will do so by using the following project setup. It has been set up with JavaScript invocations placed in different lifecycle events to demonstrate how they work.
<Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router>