阿里云主机折上折
  • 微信号
Current Site:Index > Principles of selector performance optimization

Principles of selector performance optimization

Author:Chuan Chen 阅读数:53029人阅读 分类: CSS

Selector Performance Optimization Principles

The performance of CSS selectors directly impacts page rendering speed. Browsers parse selectors from right to left, and understanding this mechanism helps in writing efficient selectors.

Avoid Overusing Universal Selectors

The universal selector * matches all elements, causing unnecessary performance overhead. Especially when nested in complex selectors, it significantly increases computational load.

/* Not recommended */
div * {
  margin: 0;
}

/* Recommended */
div > p {
  margin: 0;
}

Reduce the Depth of Descendant Selectors

Descendant selectors are one of the least performant selector types. The browser needs to check each ancestor element for a match, and deeper nesting leads to greater performance costs.

/* Not recommended */
body article section div p span {
  color: red;
}

/* Recommended */
.article-text {
  color: red;
}

Prioritize Class Selectors

Class selectors offer the best performance in modern browsers. Compared to tag selectors or attribute selectors, class selectors match faster.

/* Not recommended */
div[data-type="primary"] {
  background: blue;
}

/* Recommended */
.primary {
  background: blue;
}

Avoid Using Attribute Selectors for Fuzzy Matching

Fuzzy matching in attribute selectors (e.g., [class^="icon-"]) requires more computational resources, especially in large documents.

/* Not recommended */
[class^="btn-"] {
  padding: 5px 10px;
}

/* Recommended */
.btn-primary,
.btn-secondary {
  padding: 5px 10px;
}

Use Pseudo-Classes and Pseudo-Elements with Caution

Certain pseudo-class selectors like :nth-child() can cause the browser to recalculate layouts, impacting performance. Where possible, use classes instead.

/* Not recommended */
li:nth-child(odd) {
  background: #eee;
}

/* Recommended */
li.odd {
  background: #eee;
}

Optimize the Use of ID Selectors

While ID selectors themselves are performant, over-qualifying them can reduce performance. Use ID selectors alone without additional qualifiers.

/* Not recommended */
div#header {
  height: 80px;
}

/* Recommended */
#header {
  height: 80px;
}

Reduce the Complexity of Key Selectors

The key selector (the rightmost selector) determines matching efficiency. Keep key selectors simple and avoid complex matching.

/* Not recommended */
div.container > ul.list > li.item > a.link {
  color: blue;
}

/* Recommended */
.link-item {
  color: blue;
}

Avoid Frequent Style Modifications

Even if the selector itself is efficient, frequently modifying element styles can trigger reflows and repaints. Batch style changes for better performance.

// Not recommended
elements.forEach(el => {
  el.style.color = 'red';
});

// Recommended
const style = document.createElement('style');
style.textContent = '.dynamic-color { color: red; }';
document.head.appendChild(style);

elements.forEach(el => {
  el.classList.add('dynamic-color');
});

Leverage Browser Rendering Optimization

Certain CSS properties trigger full document reflows. Understanding these properties helps optimize selector performance.

/* Properties that trigger reflow */
.element {
  width: 100px; /* Triggers reflow */
  height: 100px; /* Triggers reflow */
  position: absolute; /* May trigger reflow */
}

/* More performant alternatives */
.element {
  transform: scale(1.1); /* Triggers repaint only */
  opacity: 0.8; /* Triggers repaint only */
}

Manage Selector Specificity

High-specificity selectors increase the difficulty of overrides, leading to more complex selectors. Maintaining low specificity benefits both maintenance and performance.

/* Not recommended */
body.home.page-about #main .content p.intro {
  font-size: 1.2em;
}

/* Recommended */
.intro-text {
  font-size: 1.2em;
}

Apply Modern CSS Techniques

Modern techniques like CSS variables and CSS-in-JS can replace some complex selector use cases, offering better performance and maintainability.

:root {
  --primary-color: #4285f4;
}

.button {
  background: var(--primary-color);
}

Optimize Preprocessor Selector Nesting

Nesting features in preprocessors like Sass/Less can easily produce over-qualified selectors, so use them cautiously.

/* Not recommended generated CSS */
body .container .main .content .article p {
  line-height: 1.6;
}

/* Recommended generated CSS */
.article-text {
  line-height: 1.6;
}

Analyze with Browser Developer Tools

Use browser developer tools' performance analysis features to identify and optimize inefficient selectors.

  1. Open Chrome Developer Tools
  2. Switch to the Performance panel
  3. Record the page loading process
  4. Analyze the Rendering and Painting timelines

Relationship Between Selectors and Rendering Layers

Understanding how browsers assign elements matched by selectors to different rendering layers helps optimize selector usage.

/* Create an independent rendering layer */
.optimized {
  will-change: transform;
  transform: translateZ(0);
}

Mobile-Specific Considerations

Mobile devices have limited processing power, requiring stricter selector optimization strategies.

/* Mobile optimization */
@media (max-width: 768px) {
  /* Simplify selectors */
  .mobile-nav {
    display: block;
  }
  
  /* Avoid complex animation selectors */
  .mobile-menu {
    transition: opacity 0.3s ease;
  }
}

Selectors and CSSOM Construction

Selector complexity affects CSSOM construction speed. Simplifying selectors speeds up CSSOM construction and page rendering.

/* Slower CSSOM construction */
div > ul > li > a > span.icon:first-child:hover::after {
  content: '';
}

/* Faster CSSOM construction */
.icon-hover-effect::after {
  content: '';
}

Selectors and GPU Acceleration

Certain CSS properties trigger GPU acceleration. Combining these properties judiciously can optimize selector performance.

.accelerated {
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

Selectors and Reflow/Repaint

Understanding how different selectors affect reflow and repaint allows for more targeted optimization.

/* Properties that trigger reflow */
.layout-change {
  width: 100px;
  height: 100px;
  margin: 10px;
}

/* Properties that trigger repaint only */
.visual-change {
  color: red;
  background: blue;
  outline: 1px solid green;
}

Selectors and Event Delegation

In JavaScript, combine selector optimization with event delegation to reduce the number of event listeners.

// Not recommended
document.querySelectorAll('.btn').forEach(btn => {
  btn.addEventListener('click', handleClick);
});

// Recommended
document.addEventListener('click', event => {
  if (event.target.closest('.btn')) {
    handleClick(event);
  }
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.