I have a Blazor Server app, I need to run a js function when the document is loaded - when I use "Static" mode, jQuery $(document).ready()
works fine but I need to use "ServerPrerendered" mode - when user click different link on the navbar, the $(document).ready() never fires because Blazor is using SingalR to update the content. The suggested way to do that is to use JSRuntime.InvokeVoidAsync("jsfunctiont")
inside
OnAfterRenderAsync
of defaultLayout.razor
but the problem is this event happens before all sub-components are fully rendered so my js function will fail.
My question is what is the way to invoke js function after all sub-components are fully rendered? which is equivalent to $(document).ready()
in Blazor server app using "ServerPreRendered" mode?
Thanks a million!
OnAfterRender
(with firstRender == true) is what you need. It will not trigger until after the whole content has been rendered in the browser.
However, after your page is created the contents will change so new components will be created and existing ones destroyed. If your jsfunction
needs to hook into every component on the page regardless of when it is created then your approach won't work. You'd need the individual components to also override OnAfterRenderAsync
and call jsfunction
passing a reference to themself.
Had the same challenge with $(document).ready()
not triggering when new components were added/removed over SignalR (using Blazor server side).
Instead of hooking into every component's OnAfterRenderAsync
and calling JsRuntime.Invoke..
I solved it by using
$(document).on('DOMSubtreeModified', function () { // doyourwork });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With