Jo Colina
Jo Colina

Reputation: 1924

Blocking DOM Parsing with JavaScript

I have a small problem. I have a table on a HTML page, which is filled by an asynchronous call in JS. There are thousands of elements, and obviously they are filled with classes and all to make them pretty :) .

This is done like so:

for(var i  = 0; i < elements.length; i++){
    var td = document.createElement("td");
    td.className = "all the pretty css";

    var button = document.createElement("a");
    button.className = "btn so pretty wow";
    td.appendChild(button);

    tableTr.appendChild(td);
}

However, this takes a lot of time, and by using console.time and console.timeEnd I was able to determine that the whole process takes about 100ms of JS execution, which means that the time is actually being queued by DOM parsing. (Am I right?)

So, I was wondering if there is any way to do something like:

Dom.stopParsing();

mySuperFunction();
anotherFunction();
thisTimeAsync(
    function(){
        Dom.parse();
);

And so, effectively reduce parsing time!

Upvotes: 0

Views: 169

Answers (1)

user663031
user663031

Reputation:

Use document fragments:

var frag = document.createDocumentFragment();

for(var i  = 0; i < elements.length; i++){
    var td = document.createElement("td");
    td.className = "all the pretty css";

    var button = document.createElement("a");
    button.className = "btn so pretty wow";
    td.appendChild(button);

    frag.appendChild(td);
}

tableTr.appendChild(frag);

Upvotes: 2

Related Questions