问题
I have a problem with high CPU load on a website where I want to replace some text with links.
The script is loaded at the end of body.
This works normally when there are no videos on the page. But if there are videos embedded like this the CPU load goes above 50%. If I use this for multiple files Firefox crashes.
<p><video width="320" height="240" class="mediaelement" autoplay="autoplay" src="video.mp4" controls="controls"><a href="video.mp4">resources/video.mp4</a></video></p>
I figured out the problem is in this, especially the readout from csv. If I just replace the text with fixed data it works as well.
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "data.csv", false);
rawFile.overrideMimeType('text/xml; charset=iso-8859-1');
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
allText = allText.split("\n");
var sizedata = Object.size(allText); //Number of entries
var sizedata = sizedata -1; //Excel +1
//alert("Debug: " + sizedata);
var i = 0;
while (i < sizedata)
{
var word = allText[i].split(";");
var wordToDefine = word[0];
var wordDefinition = word[1];
var wordToReplace = wordToDefine
var replaceItem = new RegExp(wordToReplace,"g");
document.body.innerHTML = document.body.innerHTML.replace(replaceItem, " <a href='data.html' target='_self'><span style='color:green' title='WORD'>WORD</span></a>");
i = i+1;
}
}
}
}
rawFile.send(null);
Any ideas what I can do about this? Thank you in advance.
回答1:
As @criz already mentioned, building DOM in a loop is a very bad practice. It's much better to create documentFragment and attach it to the DOM. Take a look at the https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment There is an example.
来源:https://stackoverflow.com/questions/40189823/read-and-replace-text-in-html-causes-high-cpu-load