I have a problem that I am facing while working with Blazor Server in .NET 8. My JavaScript scripts stop working correctly when I try to load the script <script src="_framework/blazor.server.js"></script>
in the _Layout.cshtml file.
When I include this script, my own JavaScript scripts stop working (they actually work for a fraction of a second, then the screen flickers and the scripts stop working). However, when I remove the references to .js files in _Layout.cshtml and place them directly in files like page1.razor, everything works fine.
File _Layout.cshtml:
<base href="~/" />
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
@RenderBody()
<script src="js/test/custom.js"></script>
<script src="js/test/swiper.js"></script>
<script src="js/test/gallery.js"></script>
<script src="js/test/Pager.js"></script>
<script src="js/test/picture.js"></script>
<script src="js/main.js"></script>
<script src="_framework/blazor.server.js"></script>
I would like all my references to JavaScript files to be contained in the _Layout.cshtml file so that they are global and work correctly across the entire page. My JavaScript scripts are intended to trigger interactions, such as .
I have already searched through threads related to similar issues, including one on StackOverflow: Why can't I load any js after my blazor.server.js?, but I couldn’t find a solution to my problem.
Has anyone encountered a similar issue and could help me? Maybe someone knows the solution to correctly load blazor.server.js in _Layout.cshtml so that my JavaScript scripts work properly across the entire page?"
2
Answers
Unfortunately, it’s not working. When I use your code, the scripts are not visible in the developer tools -> network. However, I modified your code to:
Now the scripts are visible in the developer tools -> network, but they still don’t work. The issue remains the same: when I have
<script src="_framework/blazor.server.js"></script>
in the _Layout.cshtml file, my scripts stop working.Well the issue is because Blazor Server replaces the DOM content on initialization. So to fix it you’ll need to:
Like this:
If you need to modify your existing scripts, wrap them in this:
And if script order is critical (e.g., later scripts depend on earlier ones) you might need a more sequential loading approach.