且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

释放DOM的Javascript

更新时间:2023-12-05 15:00:58

经过更多测试之后,这是我想到的:

After some more testing, here is what I came up with:

控制台不会正确显示DOM节点数.但是,它似乎也处理不正确的变量声明和删除DOM节点.如果我从脚本运行示例,则它们可以正常运行,但不能从控制台运行.

The console does correctly show the DOM node counts. It also however seems to handle variable declaration and removing DOM nodes incorrectly. If I run my examples from script, they work just fine, not from the console though.

如果我这样做:

        <script>
            var test = document.createElement('div');
            test = null;
            var test = {};
            test.node = document.createElement('div');
            delete test.node;


            var test = $('<div><div></div><div></div></div>');
            test.on("click", function(){
                alert('yes');
            });
            test.remove();
            test = null;
            //test = null;

            var test2 = {};
            test2.node = $('<div></div>');
            test2.node.remove();
            delete test2.node;
        </script>

从我的页面内部,它可以正确释放内存和孤立的DOM节点.如果我不将变量设置为NULL或将其从对象中删除,则分离的DOM节点将保留在该位置,并且由于您不再有对其的引用,因此无法将其删除.

From inside my page, it correctly frees up the memory and orphaned DOM nodes. If I do not set the variable to NULL or delete it from an object, the detached DOM node will remain there and there is no way to remove it as you don't have a reference to it anymore.

对于那些仅使用remove()函数使用jQuery的人,我认为这是一个很好的警告.

I think this is a good word of caution to those using jQuery and relying on the remove() function solely.