简体   繁体   English

如何减少DOM操作?

[英]How to reduce DOM manipulation?

As you can see from the code below, we are using innerHTML to insert html to the page. 从下面的代码中可以看到,我们正在使用innerHTML将html插入页面。 With every innerHTML, the browser will reflow and repaint which causes slowness if the we have a lot innerHTML or complex DOM. 对于每个innerHTML,如果我们拥有大量的innerHTML或复杂的DOM,浏览器将进行重排和重绘,这会导致速度变慢。 Is there a way to change the content by using only one innerHTML request? 有没有一种方法可以只使用一个innerHTML请求来更改内容? How we can increase the performance here? 我们如何在这里提高性能?

<html>
<head>
 <title>test </title>
</head>
<body>
<div id="1"> I'm div 1</div>
<div id="2"> I'm div 2</div>
<div id="3"> I'm div 3</div>
<div id="4"> I'm div 4</div>
<div id="5"> I'm div 5</div>



<script type="text/javascript">
document.getElementById("1").innerHTML='<b>Im New value 1 </b>';
document.getElementById("3").innerHTML='<b>Im New value 3  </b>';
document.getElementById("4").innerHTML='<b>Im New value 4  </b>';
document.getElementById("5").innerHTML='<b>Im New value 5  </b>';
</script>

 </body>
 </html>

Depend from where the slowness is affecting your site, at least modifying dom in one call can generate leaner css transitions, the best performance over the DOM is to have porn JavaScript with documentFragmanent as @A.Wolff said. 取决于速度的变化会影响网站的速度,至少在一个调用中修改dom可以生成更简洁的CSS过渡,因此DOM上的最佳性能是使用带有documentFragmanent的色情JavaScript,如@ A.Wolff所说。

Maybe an option is to reload sections of html as in my example, reloading/overwriting larger portions of dom you can increase the performance. 也许一个选择是重新加载html中的部分,如我的示例所示,重新加载/覆盖dom的较大部分可以提高性能。 If each dom childs are updated individual by events than you have a messy website, rethink your page group elements in modules (as in section of page), apply priority rules over events. 如果每个dom子对象都是通过事件进行更新的,而不是您的网站混乱,请重新考虑模块中的页面组元素(如页面中的部分),对事件应用优先级规则。 Try as much as possible to update large chunks of dom with one call. 一次尝试尽可能多地更新大块dom。

 var containerString = $("#wrapper").clone(); $(containerString).find('#1').html('<b>Im New value 1 </b>'); $(containerString).find('#3').html('<b>Im New value 3 </b>'); $(containerString).find('#4').html('<b>Im New value 4 </b>'); $(containerString).find('#5').html('<b>Im New value 5 </b>'); $("#wrapper").html("").append(containerString) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <html> <head> <title>test </title> </head> <body> <div id="wrapper"> <div id="1"> I'm div 1</div> <div id="2"> I'm div 2</div> <div id="3"> I'm div 3</div> <div id="4"> I'm div 4</div> <div id="5"> I'm div 5</div> </div> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM