为什么这个用户脚本会导致内存泄漏?

时间:2013-05-26 08:53:50

标签: javascript memory-leaks userscripts tampermonkey srware-iron

我的浏览器是SRWare Iron 24.0 Portable和Tampermonkey版本是2.12.3124.256或
3.0.3389.11。我写了以下用户名:

// ==UserScript==
// @name        Night Mode
// @namespace   http://use.i.E.your.homepage/
// @version     1.0
// @description  Add night mode style
// @include     http*
// @run-at      document-start
// ==/UserScript==

function addNightStyle(){
    var rules = ['html, body { background: #383838 !important; }',
        'div { background-color: #383838 !important; }',
        'header,nav,table,th,tr,td,dl,ul,li,ol,fieldset,form,h1,h2,h3,h4,h5,h6,pre { background: transparent !important;}',
        '* { color: #B6AA7B !important; }',
        'a:link,a:link *,a:link:hover,a:link:hover *,a:link:active,a:link:active * { color: #B6AA7B !important; }',
        'a:visited,a:visited *,a:visited:hover,a:visited:hover *,a:visited:active,a:visited:active * { color: #D9C077 !important; }'
        ];
    with( document.head.appendChild(document.createElement('style')) ){
        id = 'nightmode';
        for(var i=0; i<rules.length; i++){
            sheet.insertRule(rules[i], i);
        }
    }
}
setTimeout(addNightStyle,90);

当此脚本处于活动状态时,我浏览更多页面时,渲染器进程的内存使用量和虚拟大小会逐渐增加。只能通过关闭相应渲染器进程的所有选项卡来释放内存。

为什么这个脚本会导致内存泄漏?

如何解决?

1 个答案:

答案 0 :(得分:0)

首先,在这种情况下rules是关键字,您的循环甚至没有启动,您必须为规则列表选择其他名称。无论如何,根据MDN Reference - CSSStyleSheet,您无法以这种方式访问​​insertRule,但您可以这样做:

function addNightStyle(){
    var ruleList = ['html, body { background: #383838 !important; }',
        'div { background-color: #383838 !important; }',
        'header,nav,table,th,tr,td,dl,ul,li,ol,fieldset,form,h1,h2,h3,h4,h5,h6,pre { background: transparent !important;}',
        '* { color: #B6AA7B !important; }',
        'a:link,a:link *,a:link:hover,a:link:hover *,a:link:active,a:link:active * { color: #B6AA7B !important; }',
        'a:visited,a:visited *,a:visited:hover,a:visited:hover *,a:visited:active,a:visited:active * { color: #D9C077 !important; }'
        ];
    document.head.appendChild(document.createElement('style'));
    with(sheet = document.styleSheets[document.styleSheets.length - 1]){
        id = 'nightmode';
        for (var i = 0; i < ruleList.length; i++) {
            sheet.insertRule(ruleList[i], i);
        }
    }
}

工作JSFiddle