javascripthtmldomtree-nodes

Minimize DOM access inorder to have a more responsive page


Accessing DOM elements with JavaScript is slow so in order to have a more responsive page, we have to do the following things

  1. Cache references to accessed elements

  2. Update nodes "offline" and then add them to the tree

  3. Avoid fixing layout with JavaScript

Can anyone tell me how to do the first two things?

Thank You


Solution

  • These are some abstract questions, ones even that do not necessarily relate to each other.


    1. Cache references to accessed elements

    Caching references is a practice and sometimes a necessity. The act of maintaining a reference to an element locally (or, um, globally) is rather simple. When working with DOM methods like document.createElement(), there's usually a variable it's saved to. This is a reference that may be cached for later use. document.getElementById returns a reference to an element, document.getElementsByTagName returns a list of references, as does document.querySelectorAll, etc.


    2. Update nodes "offline" and then add them to the tree

    When you say "offline", I'm not quite sure the context you're referencing. Is this before whatever element (including a string like <div>) is added to the DOM?

    There are three primary ways to interact with elements:


    In terms of caching, much of that has to do with how you structure your code and use scope to your advantage. Take for example:

    window.addEventListener('load', function () {
      var target = document.getElementById('target'),
          source = document.getElementById('source'),
          ...
    
      source.addEventListener('click', function () {
        var words = source.getElementsByTagName('span'),
            total = words.length,
            word;
    
        while (word = words[--total]) {
          target.appendChild(word);
        }
      });
    
    });
    

    http://jsfiddle.net/userdude/T6YLZ/

    I keep the target and source above the click handler's scope, so that when I access them later, I already have them. Since I don't add the words to source until window.onload, I won't get all of the span elements with the words to move to target until source.click occurs.

    You seem to be describing documentFragments in your terminology. And they're cool. I've only recently come across them, although apparently for those in the know they seem to have been there for a couple years or more. So if you're one of those must.use.dom.methods(now), use documentFragments before inserting into the non-fragment DOM.

    However... Keep in mind there are times you will use elemn.innerHTML, because you're adding markup. Maybe you have templates, AJAX response markup, whatnot.

    Just don't += when elem.innerHTMLing.