We need to add anchors and highlights for some keywords/sentences in the html page. It turns out the highlighting is really slow in Firefox.
In the following code, all ranges which need to be highlighted are stored in array hiliteRanges
:
for (var i = 0; i < hiliteRanges.length; i++){
document.designMode = "on";
var selHilites = window.getSelection();
if (selHilites.rangeCount > 0)
selHilites.removeAllRanges();
selHilites.addRange(hiliteRanges[i]);
var anchorId = 'index'+i;
var insertedHTML = '<span id="' + anchorId + '" style="background-color: #FF8C00;" >'+hiliteRanges[i].toString()+'</span>';
document.execCommand('inserthtml', false, insertedHTML);
document.designMode = "off";
}
Is there any way to speed up the processing? We could have hundreds of ranges in the array hiliteRanges
. We once tried moving the designMode
setting outside of the loop, but we can see some sections are editable in the html page when the loop is running.
This is my default highlighting snippet and works fine in every browser. Try it out.
Demo: http://jsbin.com/adeneh/1/edit
And to unhighlight:
There's no need to use
document.execCommand()
for this. Just use range methods instead, and then there's no need fordesignMode
.Also, since ranges are affected by DOM mutation, I would suggest doing this part at the same time as you collect the ranges with
window.find()
. Here's an example:http://jsfiddle.net/YgFjT/