dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.66k stars 25.28k forks source link

[Blazor] Using MutationObserver for detection of DOM element removal - should observe document.body #33842

Open hakenr opened 1 month ago

hakenr commented 1 month ago

Description

A suggested approach for handling DOM cleanup tasks during component disposal is to use MutationObserver to detect element removal from the DOM and trigger the cleanup.

The sample code currently attaches the MutationObserver to target.parentNode, which works until parentNode itself is removed from the DOM. This is a common scenario, for example, when navigating to a new page, which causes the entire page component to be removed from the DOM. In such cases, any child components observing changes within the page won't be cleaned up properly.

My proposal is to modify the sample to observe document.body with the MutationObserver, as this should be a more reliable target that won’t lose mutations as easily.

However, since I’m not an expert on mutation observers, I’d appreciate feedback from the original sample author/reviewer (@MackinnonBuck?). There might be specific issues or performance considerations to keep in mind. For instance, as a performance optimization, we might want to use a single, shared MutationObserver that maintains a list of elements to track for removal, rather than creating a separate observer for every individual element.

Page URL

https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-8.0

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/javascript-interoperability/index.md

Document ID

49fa31d8-72a6-01a1-027d-6edeac9e0fc4

Article author

@guardrex

Related Issues

github-actions[bot] commented 1 month ago

🍂🎃🏮 Autumn Skies and Pumpkin Pies! 🥧☕🍂

Stand by! A green dinosaur 🦖 will arrive shortly to assist.

hakenr commented 1 month ago

@guardrex Hope everything's okay for you; looks like Hurricane Milton is causing some serious issues.

I'll put together a PR if we can agree on the best approach.

guardrex commented 1 month ago

Thanks ... I survived it! The tornadoes 🌪 were the worst part here. I just hope my fellow Americans wake up to climate change before things get vastly worse down the road.

On the issue, yes ... let's get @MackinnonBuck's input.

guardrex commented 1 month ago

UPDATE (10/29): Still no response due to high priority work for the .NET 9 release. I'll keep after them on this :smile:.

guardrex commented 1 week ago

UPDATE (11/22): @MackinnonBuck is still unavailable. He'll be here as soon as he's free (and back, as I think he's OOF 🏖 at the moment) to take a look.