- Key Takeaways
- 1. Use Best-Practice Layout Techniques
- 2. Minimize the Number of CSS Rules
- 3. Minimize DOM depths
- 4. Update Classes Low in the DOM Tree
- 5. Remove Complex Animations From the Flow
- 6. Modify Hidden Elements
- 7. Update Elements in Batch
- 8. Limit the Affected Elements
- 9. Recognize that Smoothness Compromises Performance
- 10. Analyze Repaint Issues with Browser Tools
- Frequently Asked Questions (FAQs) about Minimizing Reflows and Improving Performance
Key Takeaways
- Avoid using inline styles or tables for layout as they trigger additional reflows, instead, use best-practice layout techniques. Tables are especially expensive as the parser requires more than one pass to calculate cell dimensions.
- Minimize the number of CSS rules and the depth of your DOM tree to improve reflow speed. Tools like Unused CSS, uCSS, grunt-uncss, and gulp-uncss can significantly reduce your style definitions and file sizes.
- Make class changes on elements as low in the DOM tree as possible to limit the scope of the reflow. Also, remove complex animations from the document flow and modify hidden elements to prevent unnecessary repaints and reflows.
- Use browser tools to analyze how reflows affect performance. All mainstream browsers provide developer tools that highlight reflow and repainting times. Reducing your reflows will lead to better performance.
opacity
, background-color
, visibility
, and outline
. Repaints are expensive because the browser must check the visibility of all other nodes in the DOM — one or more may have become visible beneath the changed element.
Reflows
Reflows have a bigger impact. This refers to the re-calculation of positions and dimensions of all elements, which leads to re-rendering part or all of the document. Changing a single element can affect all children, ancestors, and siblings.
Both are browser-blocking; neither the user or your application can perform other tasks during the time that a repaint or reflow occurring. In extreme cases, a CSS effect could lead to slower JavaScript execution. This is one of the reasons you encounter issues such as jerky scrolling and unresponsive interfaces.
It’s useful to understand when reflows are triggered:
Adding, removing or changing visible DOM elements
The first is obvious; using JavaScript to change the DOM will cause a reflow.
Adding, removing or changing CSS styles
Similarly, directly applying CSS styles or changing the class may alter the layout. Changing the width of an element can affect all elements on the same DOM branch and those surrounding it.
CSS3 animations and transitions
Every frame of the animation will cause a reflow.
Using offsetWidth and offsetHeight
Bizarrely, reading an element’s offsetWidth
and offsetHeight
property can trigger an initial reflow so the figures can be calculated.
User actions
Finally, the user can trigger reflows by activating a :hover
effect, entering text in a field, resizing the window, changing the font dimensions, switching stylesheets or fonts.
The reflow processing flow hit will vary. Some browsers are better than others at certain operations. Some elements are more expensive to render than others. Fortunately, there are several general tips you can use to enhance performance.
1. Use Best-Practice Layout Techniques
I can’t believe I need to say this in 2015 but don’t use inline styles or tables for layout! An inline style will affect layout as the HTML is downloaded and trigger an additional reflow. Tables are expensive because the parser requires more than one pass to calculate cell dimensions. Usingtable-layout: fixed
can help when presenting tabular data since column widths are based on the header row content.
Using flexbox
for your main page layout can also have a performance hit because the position and dimensions of flex items can change as the HTML is downloaded.
2. Minimize the Number of CSS Rules
The fewer rules you use, the quicker the reflow. You should also avoid complex CSS selectors where possible. This can be especially problematic if you’re using a framework such as Bootstrap — few sites use more than a fraction of the styles provided. Tools like Unused CSS, uCSS, grunt-uncss, and gulp-uncss can significantly reduce your style definitions and file sizes.3. Minimize DOM depths
Slightly trickier — reduce the size of your DOM tree and the number of elements in each branch. The smaller and shallower your document, the quicker it can be reflowed. It may be possible to remove unnecessary wrapper elements if you’re not supporting older browsers.4. Update Classes Low in the DOM Tree
Make class changes on elements as low in the DOM tree as possible (i.e. elements that don’t have multiple deeply nested children). This can limit the scope of the reflow to as few nodes as necessary. In essence, only apply class changes to parent nodes such as wrappers if the effect on nested children is minimal.5. Remove Complex Animations From the Flow
Ensure animations apply to a single element by removing them from the document flow withposition: absolute;
or position: fixed;
. This permits the dimensions and position to be modified without affecting other elements in the document.
6. Modify Hidden Elements
Elements hidden withdisplay: none;
will not cause a repaint or reflow when they are changed. If practical, make changes to the element before making it visible.
7. Update Elements in Batch
Performance can be improved by updating all DOM elements in a single operation. This simple example causes three reflows:var myelement = document.getElementById('myelement');
myelement.width = '100px';
myelement.height = '200px';
myelement.style.margin = '10px';
We can reduce this to a single reflow which is also easier to maintain, e.g.
var myelement = document.getElementById('myelement');
myelement.classList.add('newstyles');
.newstyles {
width: 100px;
height: 200px;
margin: 10px;
}
You can also minimize the times you need to touch the DOM. Let’s assume you wanted to create this bullet list:
- item 1
- item 2
- item 3
<ul>
is appended, three for each <li>
and three for the text. However, a single reflow can be implemented using a DOM fragment and building the nodes in memory first, e.g.
var
i, li,
frag = document.createDocumentFragment(),
ul = frag.appendChild(document.createElement('ul'));
for (i = 1; i <= 3; i++) {
li = ul.appendChild(document.createElement('li'));
li.textContent = 'item ' + i;
}
document.body.appendChild(frag);
8. Limit the Affected Elements
Avoid situations where a large number of elements could be affected. Consider a tabbed content control where clicking a tab activates a different content block. The surrounding elements would be affected if each content block had a different height. You may be able to improve performance by setting a fixed height for the container or removing the control from the document flow.9. Recognize that Smoothness Compromises Performance
Moving an element one pixel at a time may look smooth but slower devices can struggle. Moving the element by four pixels per frame requires one quarter of the reflow processing and may only be slightly less smooth.10. Analyze Repaint Issues with Browser Tools
All mainstream browsers provide developer tools that highlight how reflows affect performance. In Blink/Webkit browsers such as Chrome, Safari, and Opera, open the Timeline panel and record an activity: A similar Timeline panel is available in the Firefox Developer Tools: The panel is named UI Responsiveness in the Internet Explorer F12 Developer Tools: All browsers display reflow and repainting times in green. The tests above were simple examples not involving significant animation yet layout rendering requires more time than other factors such as scripting. Reduce your reflows and better performance will follow. If you’ve had success in improving performance in your animations and UIs using these or other suggestions, let us know in the comments.Frequently Asked Questions (FAQs) about Minimizing Reflows and Improving Performance
What is a DOM and why is it important in web development?
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document and allows programs to manipulate the document’s structure, style, and content. The DOM represents a document as a tree of objects; these objects can be manipulated using JavaScript. A well-structured and optimized DOM is crucial for web development as it directly impacts the performance of a website. A large DOM can slow down your page load time and negatively affect your SEO ranking.
How does reducing the number of DOM elements improve performance?
Reducing the number of DOM elements can significantly improve the performance of a webpage. Each DOM element requires memory and processing power to handle, and the more elements there are, the longer it takes for the browser to render the page. By reducing the number of DOM elements, you can decrease the load on the browser and improve the page’s load time, responsiveness, and overall user experience.
What are some strategies to minimize reflows and repaints?
Reflows and repaints are browser processes that can significantly impact the performance of a webpage. Reflow happens when changes are made to the layout of a page, while repaint occurs when visual changes are made that do not affect the layout. To minimize reflows and repaints, you can use techniques such as batching DOM changes, avoiding setting multiple inline styles, using CSS transforms and opacity changes for animations, and avoiding table layouts.
How does DOM size affect Core Web Vitals?
Core Web Vitals are a set of metrics introduced by Google to measure the quality of user experience on a webpage. One of these metrics, Largest Contentful Paint (LCP), measures the time it takes for the largest content element in the viewport to become visible. A large DOM size can negatively impact LCP as it takes longer for the browser to parse and render the page. Therefore, optimizing your DOM size can help improve your Core Web Vitals scores.
What tools can I use to analyze and optimize my DOM size?
There are several tools available to analyze and optimize your DOM size. Google’s Lighthouse is a popular tool that provides a comprehensive audit of your webpage, including DOM size. Chrome DevTools also offers a range of features to inspect and manipulate the DOM. Other tools like GTmetrix and WebPageTest provide detailed performance reports and recommendations to optimize your webpage.
How does DOM size impact SEO?
DOM size can significantly impact SEO as it affects page load time, one of the key factors that search engines consider when ranking websites. A large DOM size can slow down page load time, leading to a poor user experience and lower SEO ranking. Therefore, optimizing your DOM size is crucial for improving your website’s visibility and ranking in search engine results.
How can I reduce the number of DOM elements on my webpage?
There are several strategies to reduce the number of DOM elements on your webpage. These include removing unnecessary elements, using CSS instead of HTML where possible, and optimizing your HTML code. You can also use lazy loading techniques to only load elements when they are needed, reducing the initial DOM size.
What is the ideal DOM size for a webpage?
While there is no hard and fast rule for the ideal DOM size, Google’s Lighthouse tool recommends a maximum of 1500 nodes, with a maximum depth of 32 nodes and no parent node having more than 60 child nodes. However, these are just guidelines and the optimal DOM size can vary depending on the complexity and requirements of your webpage.
How does JavaScript impact DOM size and performance?
JavaScript can significantly impact DOM size and performance as it can add, remove, or modify DOM elements. Poorly written or excessive JavaScript can lead to a large DOM size and cause performance issues. Therefore, it’s important to write efficient JavaScript and use techniques like debouncing and throttling to minimize the impact on performance.
Can CSS impact DOM size and performance?
Yes, CSS can impact DOM size and performance. While CSS itself does not add to the DOM size, the way it is used can affect the number of DOM elements. For example, using CSS to create complex layouts can lead to a large number of DOM elements. Additionally, complex CSS selectors can slow down page rendering. Therefore, it’s important to write efficient CSS and use techniques like CSS sprites and shorthand properties to minimize the impact on performance.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.