Home > Software engineering >  Svelte: Why are DOM element properties (offsetHeight, scrollHeight, etc.) valid in the beforeUpdate?
Svelte: Why are DOM element properties (offsetHeight, scrollHeight, etc.) valid in the beforeUpdate?

Time:03-15

As per this svelte tutorial: Svelte Official Tutorials, the beforeUpdate lifecycle methods runs right before the DOM is updated. And afterUpdate runs after the DOM is updated.

They are relying on the div's offsetHeight and scrollTop to know if it should scroll to show the new content.

But how does this work in beforeUpdate ? The DOM is not yet updated so the height has not changed thus it doesn't make sense to do the calculations now.

Shouldn't this be done in the afterUpdate so the DOM is updated and we get the correct offsetHeight and scrollTop ?

Also in general (not in the context of Svelte), are these properties calculated and finalized before the DOM is rendered using the DOM tree?

CodePudding user response:

You are correct about the scheduling of beforeUpdate and afterUpdate. But the Svelte tutorial code is correct anyway, because the logic is this:

  1. In beforeUpdate, check if the scrollbar/position is near the bottom of the scroll container
  2. In afterUpdate, only scroll to the bottom if the check in beforeUpdate returned true. This is done to not scroll to the bottom if the user scrolled up and then enters a new message - in that case, he likely wants to stay at that position.
  • Related