Quinton Pike
Quinton Pike

Reputation: 3861

JS Memory leaks with AJAX app and event listeners?

So I am making a complex project management system that is build completely in AJAX. With hash navigation the site loads and removes a lot of HTML and adds a lot of event listeners on each load.

My question is, does modern browsers garbage collect the event listeners after those elements have been $.remove'd.

If not, is it better to use onclick="doFunction();" instead to prevent adding event listeners? I rather not do it this way, but if it will prevent memory leaks it might be the best option.

Any help would be greatly appreciated.

Thanks!

Upvotes: 2

Views: 231

Answers (2)

Greg Pettit
Greg Pettit

Reputation: 10830

Using onclick is not the way to go. jQuery is a great option, especially if it's going to prove useful throughout your application. If you're using it ONLY for Ajax, you can probably find smaller libraries to do the job.

If you want to use jQuery, I would strongly recommend using .on() instead of adding event listeners on each load. If you use .on() for delegates (replacing the deprecated but still functioning .delegate() method) you will not need to rebind them with each load, which will virtually eliminate the possibility of leaks due to binding/unbinding spaghetti.

Upvotes: 2

Tadeck
Tadeck

Reputation: 137430

No, it is better to add event listeners using jQuery, because jQuery deals with possible memory leaks.

Upvotes: 2

Related Questions