简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM