Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Server App $(document).ready() equivalent

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!

like image 756
John Lee Avatar asked Mar 02 '23 01:03

John Lee


2 Answers

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.

like image 147
Peter Morris Avatar answered Mar 27 '23 17:03

Peter Morris


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 });

like image 44
Howie Avatar answered Mar 27 '23 17:03

Howie