简体   繁体   中英

Will this cause a browser memory leak?

I create a couple divs with an onclick event on them as children of 'parentDiv'. In the future, I set parentDiv.innerHTML = 'xyz' where xyz is more divs with onclick events, which replace the old ones.

My question: will any browsers leak memory because I did not remove the onclick events of the the old div's before removing them from the dom?

I would suggest reading up on memory leaks as explained by Douglas Crockford. The article gives you detailed examples of memory leaks and even a nice purge function allowing you to overcome the issues associated with them. Enjoy!

Usually no.

However, if your onclick handler happens to be closure which references the HTML element it is attached to, then it could leak in some browsers.

Have a look at this guide I wrote for more details on JavaScript memory leaks and how to find and fix them: http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html . That should clear things up for you.

If you remove them from the DOM then any event handlers should be removed from them as well and not cause a leak.

Douglas Crockford has some excellent writing on JavaScript Memory Leaks . Well worth the read.

No, this is up to the browser to manage. As objects are removed, the browser will (or at least should) free up associated memory. I wouldn't bank on it though.

In any case, unless you are doing this thousands of times, I wouldn't expect it to be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM