简体   繁体   English

这会导致浏览器内存泄漏吗?

[英]Will this cause a browser memory leak?

I create a couple divs with an onclick event on them as children of 'parentDiv'. 我创建了几个带有onclick事件的div作为'parentDiv'的子项。 In the future, I set parentDiv.innerHTML = 'xyz' where xyz is more divs with onclick events, which replace the old ones. 在将来,我设置parentDiv.innerHTML = 'xyz' ,其中xyz是更多div与onclick事件,取代旧的事件。

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? 我的问题:任何浏览器都会泄漏内存,因为在从dom中删除之前我没有删除旧div的onclick事件吗?

I would suggest reading up on memory leaks as explained by Douglas Crockford. 我建议阅读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. 但是,如果你的onclick处理程序恰好是引用它所附加的HTML元素的闭包,那么它可能会在某些浏览器中泄漏。

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 . 看看我写的这本指南,了解有关JavaScript内存泄漏以及如何查找和修复它们的更多详细信息: 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. 如果从DOM中删除它们,那么任何事件处理程序也应该从它们中删除而不会导致泄漏。

Douglas Crockford has some excellent writing on JavaScript Memory Leaks . Douglas Crockford在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. 无论如何,除非你这样做了数千次,否则我不会指望这是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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