killereks
killereks

Reputation: 189

Poor JavaScript rendering performance

In my project I do lots of HTML manipulation via JavaScript, multiple times a second I'm attempting to add new HTML, edit existing one and delete other HTML. This is what a sample function that creates HTML looks like:

function getItemInventoryHTML(item){
    var color = Idle.getRarityColor(item.rarity);
    return `<div class="card" id="item-${item.uniqueID}">
               <div class="ui segment basic full-height">
                 <div class="ui ${color} top attached label">[<span class="item-amount">${item.amount}</span>] ${item.name}</div>
                    <div class="ui grid full-height">
                       <div class="six wide column">
                          <img class="ui fluid image ${item.enchantments.length > 0 ? "enchanted" : ""}" src="${item.image}">
                        </div>
                        <div class="ten wide column">
                          ${item.GetEnchantDesc()}
                        </div>
                      </div>
                    </div>
               <button class="ui button green fluid tiny bottom attached" onclick="game.inventorySell('${item.uniqueID}');">Sell for ${Idle.FormatNumber(item.price)} ${Idle.Image(icon.gold,16,16,"ui avatar image")}</button>
               </div>
            </div>`;
  }

This function would be in a for loop collecting all of the HTML into a variable and then I create it using .innerHTML = html; But the performance is very poor, according to google chrome the browser spends about 500ms on 'Recalculate Style' and 'Rendering'.

What can I do to push the performance, or force the browser to only render newly created HTML ?

Upvotes: 0

Views: 233

Answers (1)

Mat Sz
Mat Sz

Reputation: 2552

Updating innerHTML is generally computationally expensive since the browser has to parse the code on each update.

What you should do is to create the elements with JavaScript (document.createElement), store the references to them for later modification/deletion, and append them to your container element. But at this point, you're basically reinventing UI libraries like React.

With innerHTML = x there's no way to notify the browser of which elements are new and which aren't (or maybe which old elements have changed). The browser doesn't check for similarities between old and new data.

Upvotes: 2

Related Questions