Race Condition? Fetching an element by ID of a view which is yet to be rendered

Hi, its not a race condition as such - that is when two threads make competing updates. Javascript in the browser is single threaded, so there can be no race conditions. I can see what you describing though, it takes a little time for the view to render, and you would like to know when an element has been rendered so that you can ask for its size.

I think what you need is a MutationObserver: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

You could hook that up through ports, to listen for when your element has been added to the DOM?

You could also try onAnimationFrame: https://package.elm-lang.org/packages/elm/browser/latest/Browser-Events#onAnimationFrame. If you wait at least until the next animation frame before making your first request to get the element, it is more likely to be present, but I don’t think it is guaranteed to be present, so you might still have to keep trying until you get it.

I think the MutationObserver approach is going to be more robust - as far as I know there is no kernel package that wraps it so you’d need the ports.

I think you could also build some custom HTML element that fires an event when your element is added to it? Then listen to that event through Html.Events.on: https://package.elm-lang.org/packages/elm/html/latest/Html-Events#on

1 Like