0
0
SASSmarkup~8 mins

@while loop usage in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: @while loop usage
MEDIUM IMPACT
This affects CSS generation time and final CSS file size, impacting page load speed and render time.
Generating repetitive CSS rules with a loop
SASS
.item {
  @for $i from 1 through 100 {
    &-#{$i} {
      width: 10px * $i;
    }
  }
}
Groups selectors under one parent, reducing repetition and improving maintainability.
📈 Performance GainSaves ~2kb in CSS size, reduces parsing time, improves LCP.
Generating repetitive CSS rules with a loop
SASS
$i: 1;
@while $i <= 100 {
  .item-#{$i} {
    width: 10px * $i;
  }
  $i: $i + 1;
}
Generates 100 separate CSS rules, increasing CSS file size and slowing page load.
📉 Performance CostAdds ~5kb to CSS bundle, increases LCP due to larger CSS parsing.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
@while loop generating many classesNone (CSS only)NoneHigh due to large CSS size[X] Bad
@for loop with grouped selectorsNone (CSS only)NoneLower due to smaller CSS size[OK] Good
Rendering Pipeline
Sass @while loops run during CSS preprocessing, generating CSS before the browser loads the page. Large loops create bigger CSS files, increasing download and parse time.
Network
Style Calculation
⚠️ BottleneckNetwork download and Style Calculation due to large CSS files
Core Web Vital Affected
LCP
This affects CSS generation time and final CSS file size, impacting page load speed and render time.
Optimization Tips
1Avoid generating excessive CSS rules with large @while loops.
2Group selectors to reduce repetition and CSS file size.
3Check CSS file size in DevTools Network panel to monitor impact.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance risk of using a large @while loop in Sass?
ACausing many DOM reflows during page interaction
BGenerating a very large CSS file that slows page load
CIncreasing JavaScript bundle size
DSlowing down server response time
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, filter by CSS files, and check CSS file size.
What to look for: Large CSS file size indicates heavy loop-generated CSS; smaller files load faster.