Skip to content Skip to sidebar Skip to footer

Chrome Extension - Best Method Of Reducing Load Time While Using Content Scripts

I'm building a chrome extension that is supposed to look through an array of over 12,000 values and compare it to the webpages p tags, and if a value from the array is inside the p

Solution 1:

Updatehttp://jsfiddle.net/r4bnxemL/3/

This new approach is less complicated and it doesn't merge each word into one big regex. Instead it just uses asycn looping method using setTimeout trick.

var words = ['dolor', 'sit', 'odio'];

var ele = document.getElementById('text'),
    html = ele.innerHTML;


asycnIterator(words,
    function (word) {
        var reg = newRegExp('\\b' + word + '\\b', 'ig');
        html = html.replace(reg, '<span class="marked">' + word + '</span>');
    }, function () {
        ele.innerHTML = html;
});

functionasycnIterator(arr, func, cb) {
    var i = 0;

    nextCall();

    functionnextCall() {
        func(arr[i++]);
        if (i >= arr.length) {
            if (cb) cb();
            return;
        }
        setTimeout(nextCall, 1);
    }
}

First of all there are two things you could do first break the loop into tiny pieces it will probably make the whole process finish a bit in more time BUT it won't block everything else, Javascript single threaded so use event loop.

You can do it using setTimeout for example. (note will need to use callback pattern as it will return immediately, next line's execution wont wait for loop to finish)

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

Second thing you can do is make looking up faster. For that matter the more native method you use the better it's going to be. This is just my approach

  1. join all array elements into a string
  2. then search using them as regex
  3. store the indexes

This following function does that and invokes cb with list of all occurrences.

functionreturnOccurences(str, arr, cb) {
    var ele = null,
        index = 0,
        occurences = [],
        regexp = '\\b' + arr.join('\\b|\\b') + '\\b';

    getNextWord();
    functiongetNextWord() {
        ele = str.substr(index).match(newRegExp( 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
    }
}

String match function docs MDN LINK It if is not invoked with parameter g for regex than it return array with non enumerable properties which are index of the word found and input that contains the original text.

We can use index to parse further the string ahead after first match.

Post a Comment for "Chrome Extension - Best Method Of Reducing Load Time While Using Content Scripts"