-1

我的浏览器是 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);

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

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

如何解决?

4

1 回答 1

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

于 2013-05-26T09:31:39.077 回答