Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow detached autosize DOM elements to be garbage collected #410

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

blutorange
Copy link

The proper way is to use autosize.destroy when an autosize instance is no longer needed.

However, sometimes it may be hard to explicitly destroy existing widget instances. See for this issue from another widget where the DOM element or DOM container element is simply removed. For example, try creating a simple demo page with a div container and some textareas with autosize, then remove the div container from the DOM. The assignedElements still contains all entries, and the memory tab of the dev tools shows many detached DOM elements that weren't garbage collected.

This happens because of 2 reasons: (a) The assignedElements map keeps a hard reference to all DOM textareas and the autosize instances; (b) each instances adds a global resize event listener to the window, and the event listener captures the textarea DOM element with a closure.

There is a simple change that solves these issues:

  • Use a weak map instead of a map. Supported in all modern browsers, for somewhat older browsers, we can still fall back to a map.
  • Use a resize observer instead of a global event listener, as already mentioned in the code as a todo. Resize observer won't prevent the observed DOM elements from getting garbage collected. As a bonus, it will now also properly resize when the width is changed in any other. A global resize listener can still be used as a fallback when the environment does not support resize observers.

Use weak map + resize observer to make DOM + state so that an autosize
instance does not prevent the DOM node from getting garbage collected.
@lofcz
Copy link

lofcz commented Sep 3, 2024

thanks for working on this, pulled locally and tested - works fine. Hope this gets merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants