Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Created May 10, 2022 07:32
Show Gist options
  • Save yyx990803/e7591380f38bbb8e309de8fd1f4010a4 to your computer and use it in GitHub Desktop.
Save yyx990803/e7591380f38bbb8e309de8fd1f4010a4 to your computer and use it in GitHub Desktop.
Weird detached element memory issue in Chrome
<div id="app">
<button id="reset">reset</button>
<button id="outer">no leak</button>
<div id="container">
<button id="inner">leak</button>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
</div>
<script>
const unmount = () => {
document
.getElementById('app')
.removeChild(document.getElementById('container'))
}
// does not leak
document.getElementById('outer').addEventListener('click', unmount)
// causes leak
document.getElementById('inner').addEventListener('click', unmount)
document.getElementById('reset').addEventListener('click', () => {
const c = document.createElement('div')
c.id = 'container'
c.innerHTML = `
<button id="inner">leak</button>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
`
c.querySelector('#inner').addEventListener('click', unmount)
document.getElementById('app').appendChild(c)
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment