5

Anyone know how long window event listeners are supposed to persist?

My initial thoughts are that any attached to the document are probably lost after a page reload while those attached to the window object I would expect to persist over a page reload.

However testing seems to indicate that all event listeners are destroyed when the page is reloaded, is this correct?

0

1 Answer 1

18

The listeners for an event on an element will persist as long as:

  1. They are not removed.

  2. The element continues to exist.

Reloading the page destroys the page's current elements and builds new ones from scratch, so event listeners don't survive that. (It also destroys the JavaScript environment that was associated with the page. So if the handlers were in that environment, they stop existing too.)

Sign up to request clarification or add additional context in comments.

6 Comments

Some what more described than my comment, upvoted and comment deleted.
Thanks T.J. Crowder, so a reload destroys the Javascript environment which would explain why window.addEventListener events are getting destroyed on a reload. Very helpful explanation.
@NickC: Don't skip the bit about the elements, that's just as much a source of the disconnect as the other. If you destroy the elements without destroying the JavaScript environment (for instance, via innerHTML), the handlers still get disconnected.
Do the event listeners persist if a new page is navigated to in the stack? (traditional web-dev). I would image so. What about single page apps like those you would build with React? Since the page never reloads, just the data, we must clean up our event listeners in callback functions. Right?
@JoMomma - "Do the event listeners persist if a new page is navigated to in the stack? (traditional web-dev)." No, b/c the element doesn't exist anymore. "What about single page apps like those you would build with React? Since the page never reloads, just the data, we must clean up our event listeners in callback functions. Right?" It depends how you attached the listeners. If you did it with React's onXyz properties, then no, you don't. If you actually used addEventListener (e.g., in componentDidMount) then yes, it's best if you use removeEventListener (e.g. in...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.