chrome扩展-在使用内容脚本时减少加载时间的最佳方法

chrome extension - best method of reducing load time while using content scripts

本文关键字:加载 时间 方法 最佳 脚本 扩展 chrome      更新时间:2023-09-26

我正在构建一个chrome扩展,它应该遍历一个超过12000个值的数组,并将其与网页p标记进行比较,如果数组中的值在p标记内,它应该突出显示文本,当悬停时,它应该显示一些信息。因此,我认为使用内容脚本很容易,但使用"run_at": "document_end"会使网页加载速度慢3倍,用我的扩展程序加载几乎多10秒。显然并不理想。

顺便说一下,这是我的内容脚本代码:

jQuery(document).ready(function($) {
var $all_p = $("p");
$.each(arrayObj, function(key, value) {
      $all_p.highlight(key, {caseSensitive: true, className: 'highlight-882312', wordsOnly:true });
});
$('.highlight-882312').each(function() {    
    var currentKey = $(this).text();
    console.log(currentKey);
        //Create tooltip on hover.
        Tipped.create(this, "<iframe id='cardiFrame' src='https://mywebsite.com/word?q="+footballers[currentKey]+"'></iframe>", {
            skin: "white",
            hook: 'rightmiddle',
            maxWidth: 306,
            maxHeight: 365,
            background: '#eee',
        }); 
});
});

不管怎样,这对我来说太慢了,但我仍然想构建扩展,所以我想我可以向我的后台/弹出窗口发送一个所有p标签的数组,以便在后台/弹出框中循环查找关键字,然后在弹出框中显示匹配的关键字,并向匹配关键字的内容脚本发送消息,以便突出显示它们。这会减少加载时间吗?这对我的问题来说是一个很好的解决方案吗,因为额外的10秒加载时间根本不理想?

如果有任何建议,我将不胜感激。

编辑:数组对象:

var arrayObj = {
"word1": 'word_word1',
"word2": 'word_word2',
"word3": 'word_word3',
// extra 12K lines...
}

Manifest.json:

我的清单很典型,但内容脚本信息是:

 "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "css": ["styles.css", "tipped.css"],
      "js": ["jquery.min.js", "jquery-highlight1.js", "spinners.min.js", "tipped.js", "word.js", "script.js"],
      "run_at": "document_end"
    }
  ],

更新http://jsfiddle.net/r4bnxemL/3/

这种新方法不那么复杂,而且它不会将每个单词合并到一个大的正则表达式中。相反,它只是使用了使用setTimeout技巧的asycn循环方法。

var words = ['dolor', 'sit', 'odio'];
var ele = document.getElementById('text'),
    html = ele.innerHTML;

asycnIterator(words,
    function (word) {
        var reg = new RegExp('''b' + word + '''b', 'ig');
        html = html.replace(reg, '<span class="marked">' + word + '</span>');
    }, function () {
        ele.innerHTML = html;
});
function asycnIterator(arr, func, cb) {
    var i = 0;
    nextCall();
    function nextCall() {
        func(arr[i++]);
        if (i >= arr.length) {
            if (cb) cb();
            return;
        }
        setTimeout(nextCall, 1);
    }
}

首先,你可以做两件事——首先把循环分解成小块——这可能会让整个过程在更长的时间内完成,但它不会阻塞其他一切,Javascript单线程,所以使用事件循环。

例如,您可以使用setTimeout来完成此操作。(注意,需要使用回调模式,因为它会立即返回,下一行的执行不会等待循环完成)

var arr = [1,2,3....100000];
var i = 0 ;
nonBlockingAsycnLoop(); //will prints all values in console without blocking
function nonBlockingAsycnLoop() {
   console.log(arr[i++]);
   setTimeout(nonBlockingAsycnLoop,0);
}

你能做的第二件事就是加快抬头的速度。就这一点而言,你使用的原生方法越多越好。这只是我的方法

  1. 将所有数组元素连接到一个字符串中
  2. 然后使用它们作为正则表达式进行搜索
  3. 存储索引

下面的函数执行此操作,并使用所有出现的列表调用cb。

function returnOccurences(str, arr, cb) {
    var ele = null,
        index = 0,
        occurences = [],
        regexp = '''b' + arr.join('''b|''b') + '''b';
    getNextWord();
    function getNextWord() {
        ele = str.substr(index).match(new RegExp( regexp , 'i'));
        if (!ele) {
            cb(occurences);
            return;
        }
        occurences.push({i: ele.index, len: ele[0].length, word: ele[0]});
        index = ele[0].length + ele.index;
        setTimeout(getNextWord,0); //makes it non blocking
    }
}

字符串匹配函数docs MDN LINK如果不使用regex的参数g调用,则返回具有不可枚举属性的数组,这些属性是找到的单词和包含原始文本的输入的索引。

我们可以在第一次匹配之后使用index来进一步解析前面的字符串。