开发者

Deleting DOM nodes in JavaScript to save Memory

开发者 https://www.devze.com 2023-02-12 07:52 出处:网络
I am using Safari browser for viewing my Web Page which is rich in Javascript. I see Safari takes a lot of memory (500-900 MBs) while viewing the web page and do开发者_高级运维ing various operations.

I am using Safari browser for viewing my Web Page which is rich in Javascript. I see Safari takes a lot of memory (500-900 MBs) while viewing the web page and do开发者_高级运维ing various operations. I wish to know whether deleting the DOM objects created, using say, var elem = document.getElementById('Id1'); needs to be deleted for optimizing this memory utilization? If any other pointers, please suggest. Also, how can we delete this DOM object in the simplest way?

Thanks Siddharth


One point of clarification. Your example code does not create a DOM node; it merely retrieves a reference to an existing node:

var elem = document.getElementById('Id1');

Once you have access to the element you can remove it like this:

elem.parentNode.removeChild(elem);


Deleting DOM nodes may be useless if you're creating memory leaks (they may not be cleared from memory).

This can happen if you connect DOM nodes & javascript objects within your code (circular references that won't be cleared by DOM and JS Garbage Collectors).

If you want to get rid of this problem:

  • use the tools mentionned by this answer
  • read a little bit on DOM/JS memory leaks if you want to avoid future leaks and recognize this anti-pattern.


The webkit inspector has a profiler utility for this kind of thing. I'm not sure if it exists in the Safari version but it's definitely in the Chrome version.

See this question/answer.

Here is a good tutorial on using the Safari Inspector utility.

0

精彩评论

暂无评论...
验证码 换一张
取 消