如何在不阻止的情况下处理文档中的所有HTML标记?

时间:2015-04-14 19:54:53

标签: javascript html google-chrome dom google-chrome-extension

我正在开发Chrome扩展程序,使用户能够根据有关网站内容的简单规则来操纵网站的外观。问题是我必须扫描并分类文档中的每个标记,这可能是一个很慢的过程。我正在寻找一种方法来做到这一点,而不会阻止页面呈现并减慢用户的体验过多。

现在我的内容脚本看起来像这样:

function init() {
  tagObserver = new MutationObserver(function(mutations, obs) {
    for(var i=0; i<mutations.length; ++i) {
      for(var j=0; j<mutations[i].addedNodes.length; ++j) {
        var newTag = mutations[i].addedNodes[j];
        if (newTag.querySelectorAll) {
          Array.prototype.forEach.call(
            newTag.querySelectorAll('*'),
            testTags);
        }
      }
    }
  });
  Array.prototype.forEach.call(
    document.querySelectorAll('*'),
    testTags);
  tagObserver.observe(document.documentElement, {
    childList: true,
    subtree: true
  });
}

function testTags(tag) {
  sleep(5);
  tag.style.backgroundColor = '#FFF';
  tag.style.color = '#FFF';
}

function sleep(ms) {
    var date = Date.now();
    var curDate = null;
    do {
        curDate = Date.now();
    } while (curDate-date < ms);
}

init();

在这种情况下,testTags是占位符函数,表示实际的,可能很慢的分类代码。如果我使用它,它会减慢每个页面的渲染速度。如何尽可能多地从渲染路径中拉出来以便为普通用户提供足够快的页面绘制?如果标签需要一些时间进行分类是可以接受的,但我不想等到页面完全完成渲染之后才开始修改任何内容。

0 个答案:

没有答案