Reputation: 11
The project is to process and visualize high dimensional data. And we need to replace some text after the data has been loaded to the website. I found some threads on stackoverflow with more or less the same solution Replace text in HTML page with jQuery:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('-9o0-9909','The new string');
});
And this solution works well, it replaces exactly the searched text (regex) with the html code (e.g. 'word').Adding superscript tags around all trademark and registered trademark symbolsReplace ALL words in HTML or Swapping text in a DOM element with children JavaScript/jQuery. The problem is that we have to replace 10,000+ words and it takes a while. The time is not the issue, but the browser freezes during that process and you can't do anything. How can we avoid freezing the browser? I read about lazy loading for images and asynchronous functions, but I don't know how to apply this to text replacement. Any help is appreciated?
Edit: Here a jsfiddle
Upvotes: 1
Views: 1249
Reputation: 24191
Whenever you manipulate the DOM directly, it's often slow because the browser may try to do a document reflow as your updating.
To prevent this, one idea is just to remove the section from the DOM, and then manipulate it while it's detached, and when done just re-attach back to the DOM, the browser will then only need to do 1 single document reflow.
Below is a simple example, I create some 100,000 char dummy HTML with random X
s in, you can then click the button and it will then surround all the X
with the B
(bold) tag. And as you will see when you click the button it's pretty much instant.
const d = document.createElement('div');
const a = (new Array(100000)).fill('_');
for (let l = 0; l < a.length; l += 1) {
const r = Math.random();
if (r < 0.1) a[l] = '<br/>'
else if (r < 0.2) a[l] = 'X';
}
d.innerHTML = a.join('');
document.body.appendChild(d);
document.querySelector('button').addEventListener('click', () => {
d.remove();
d.innerHTML = d.innerHTML.replace(/X/g, '<B>X</B>');
document.body.appendChild(d);
});
<button>Bold X</button>
Upvotes: 1