Effective Javascript for DOM Modifications

Let's say I have an HTML file that I want to process using Javascript. For instance:

  • Add some DOM elements, such as wrappers spanor div.
  • Change the style of the document, for example, the size of the base font, line height, etc.
  • Use a defender to add objects ­.

What would be the most efficient way to do this, i.e. I would like to do this with a minimal number of transitions.

An ideal case would be to run the JS code even before the first layout. Is it possible? I know, as a rule, it’s a bad idea to execute expensive scripts before the page has been displayed for this, will make the page look blank for some time, and this is a really bad experience. However, I will need this to work offline, and this will not be a problem for my project.

Or, is there a way to make all the dom modifications in one group, i.e. after all changes are over, will re-planning take place?

+5
source share
4 answers

. , - , , - /.

DOM

DOM, , .

, , , DOM, .

var container = document.createElement('section'); //not in the DOM yet
//do some extensive work here to prepare the doc
document.body.appendChild(container); //now we go to the DOM, causing a single re-paint

, (). , DOM, .

, . , DOM- , , , REGEX'ing ( HTML), .

, , , -. DOM, , , , .

+6

documentElement document, document.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>...</title>           
    </head>
    <body>
        <script type='text/javascript'>
var docElem = document.documentElement,
    parentNode = docElem.parentNode,
    nextSibling = docElem.nextSibling;
parentNode.removeChild(docElem); // reflow
// ...
docElem.lastChild.appendChild(docElem.ownerDocument.createElement('hr'));
// ...
parentNode.insertBefore(docElem, nextSibling); // reflow
        </script>
    </body>
</html>

.

jsFiddle

+3

, , . script. , , , div , DOM. documentFragment , . , , , .

Fragment: http://ejohn.org/blog/dom-documentfragments/

0

, u DOM . , . , . :

, .

-1

All Articles