- Optimize page load times
- HTML tag order: move all movable <script> tags to html </body> before.
- GZIP encoded transmission of JavaScript files
- downsizing, obfuscation, and compiling, using tools to streamline and optimize your code
- Delay loading JavaScript files when requested
- to optimize the operation of document objects
- implement minimal access to page elements
- Save a reference to a DOM element with a variable for subsequent use
- access child DOM elements by reference to a separate parent element
var wrapper = Document. getElementById ("wrapper" = Wrapper.getelementbytagname ("header") [0< span style= "color: #000000", nav = wrapper.getelementbytagname ("nav") [0]; view code
- add a DOM modification to a new element before adding it to the current live page
-
var list = document.createelement ("ul" = document.createelement ("li" = "this is a list item" ;list.appendchild (item);d ocument.body.appendChild (list); view code
-
- Use existing elements as much as possible
- If you are creating multiple elements with similar label attributes, you can use the CloneNode () method of the DOM element to copy the element and related attributes, and to reduce the standard document.createelement () method to create the Element.
- The use of offline DOM
Use CSS instead of JavaScript to manipulate page styles, reducing the number of times the browser raises reflow
// demonstrates the reflow that is thrown when you directly update the Style property of a DOM element var nav =document.getelementbytagname ("nav"); = "#000"; // raise a reflow in the browser Nav.style.color = "#fff"; // raises a single reflow Nav.style.opacity = 0.5; // raises a single reflow
View Code// Apply CSS classes to DOM elements to reduce browser rearrangement var nav = document.getelementbytagname ("nav"); Nav.classname= "selected"; // a CSS class called selected contains multiple styles
View Code// to reduce the occurrence of browser reflow by hiding elements and modifying the style properties of elements var nav = document.getelementbytagname ("nav"); = "none"; // hides the element, raises a browser reflow Nav.style.backgroundColor = "#000"; // the reflow is not raised because the element is hidden Nav.style.color = "#fff"; // does not cause the browser to Reflow Nav.style.opacity = 0.5; // does not cause the browser to Reflow Nav.style.display = "block"; // causes the element to be displayed again, causing the browser to reflow
View Code
- Improve DOM Event performance
- Delegate event to parent element
- Using framing to handle frequently-sent events
JavaScript Performance Optimizations