javascript - 每秒扫描页面查找关键字是否有效?

标签 javascript jquery html optimization memory-efficient

所以我正在为自己和一些 friend 编写个人用户脚本。用户脚本用于阻止页面上的关键字。

要在我使用的页面上搜索关键字:

var filter = ["worda", "wordb", "wordc"];
var found = false;

var check =
    function () {
        //Stores the content of the head and body in the document.
        var head = $("head").html();
        var body = $("body").html();


        $.each(filter, function(index, item) {
            if ((head + body).toString().toLowerCase().contains(item.toLowerCase()))  {
                window.clearInterval(interval);
                console.log("Found: " + item);
                found = true;
                return false;
            }
        });

        if (found) {
            $("body").hide();
            var originalTitle = $(document).prop("title");
            $(document).prop("title", "Blocked");

            window.setTimeout(function() {
                if (confirm("This page contains a blocked keyword, are you sure you'd like to continue?")) {
                    $(document).prop("title", originalTitle);
                    $("body").show();
                    return;
                }
            }, 1);
        }
    };

然后我将其设置为每秒重复一次:

var interval = window.setInterval(check, 1000);

我每秒重新检查页面的原因是因为新内容可能是通过 Javascript 动态创建的,我需要确保它也被过滤。

但是,我想知道这是否是扫描页面关键字的最有效方法,或者是否有更有效的方法不需要我重新检查整个页面(可能只需要重新检查新元素)。

此外,我想将时间间隔推得尽可能低(我想大约 100 毫秒),但我不知道这是否非常节省资源。

感谢您的帮助。

最佳答案

您是对的,定期扫描页面内容是解决问题的低效方法。话虽这么说,如果它每秒只运行一次,那可能没什么大不了的。

不过,还有更好的选择。 MutationObserver接口(interface)可用于在文档或文档的一部分被修改时触发事件。这非常适合您想要做的事情:

var observer = new MutationObserver(function() {
    … scan the document for your keywords …
});
observer.observe(document, {
    childList: true,
    characterData: true,
    subtree: true
});

关于javascript - 每秒扫描页面查找关键字是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911980/

相关文章:

javascript - 绑定(bind)方法不起作用

javascript - HTML 中的 div 不是一一显示的吗?

javascript - 鼠标悬停更改图像

javascript - Typescript 无法推送到 knockout 可观察数组,因为即使在初始化后也未定义

javascript - 使用回调返回数据后,函数仍然捕获来自其他函数的错误

jquery - 我无法输入内容

javascript - 两个(独立的)jQuery Tab 插件杀死了我的代码

javascript - 页面更改未保存(在页面重新加载时)

html - 在 CSS 中使用 @font-face 使用 OS 9 资源分支字体

javascript - D3 从最右边的字符对齐轴左侧的文本