在HTML中读取和替换文本会导致高CPU负载 [英] Read and replace text in HTML causes high CPU load
问题描述
我在网站上遇到高CPU负载问题,我想用链接替换一些文本。
I have a problem with high CPU load on a website where I want to replace some text with links.
脚本在主体末尾加载。
当页面上没有视频时,此功能正常。但如果有像这样嵌入的视频,CPU负载超过50%。如果我将它用于多个文件,Firefox会崩溃。
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>
我发现问题在于此,特别是csv的读数。如果我只是用固定数据替换文本,它也可以工作。
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.
推荐答案
正如@criz已经提到的,在循环中构建DOM是一种非常糟糕的做法。创建documentFragment并将其附加到DOM会好得多。请查看 https://developer.mozilla.org/ en-US / docs / Web / API / Document / createDocumentFragment 有一个例子。
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.
这篇关于在HTML中读取和替换文本会导致高CPU负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!