简体   繁体   中英

How to reduce DOM manipulation?

As you can see from the code below, we are using innerHTML to insert html to the page. With every innerHTML, the browser will reflow and repaint which causes slowness if the we have a lot innerHTML or complex DOM. Is there a way to change the content by using only one innerHTML request? 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.

Maybe an option is to reload sections of html as in my example, reloading/overwriting larger portions of dom you can increase the performance. 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. Try as much as possible to update large chunks of dom with one call.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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