Skip to content

Instantly share code, notes, and snippets.

@HaQadosch
Last active February 27, 2017 11:40
Show Gist options
  • Select an option

  • Save HaQadosch/aafb8c796cb6c791646447b71adfa1ba to your computer and use it in GitHub Desktop.

Select an option

Save HaQadosch/aafb8c796cb6c791646447b71adfa1ba to your computer and use it in GitHub Desktop.
Front End Best Practice

It may be more efficient to

  • first clone the entire DOM Node
  • make the changes to the clone
  • then replace the original with it

so you avoid multiple redraws and lower the CPU and memory load It also prevents ‘jittery’ changes to your page and Flashes Of Unstyled Content (FOUC).

// Efficiently manipulating a node by cloning it
var element = document.querySelector(".my-node");
var elementClone = element.cloneNode(true);
// (true) clones child nodes too, (false) doesn't
elementClone.textContent = "I've been manipulated...";
elementClone.children[0].textContent = "...efficiently!";
elementClone.style.backgroundColor = "green";
element.parentNode.replaceChild(elementClone, element);

Just be careful when cloning because it doesn’t clone event listeners. Sometimes this can actually be exactly what you want. In the past we have used this method to reset event listeners when they weren’t calling named functions and we didn’t have JQuery’s .on() and .off() methods available. I guess this also works for small area of the DOM.

@HaQadosch

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment