Sass – the irresponsible loops
As Uncle Ben says
With great power comes great responsibility
Pre-processors are pretty popular these days for writing CSS, the enhancements they bring to CSS authoring is a great addition even if it’s just for variables (yes I know of CSS variables). There are also a ton of other features available in such tools.
One such great item is the ability to write loops, for those not familiar with loops in programming they provide the ability to write code that repeats the block of code within the loop multiple times based on a set of conditions. That’s a pretty basic explanation, and loops can provide great power for repeated tasks.
With that last point, “great power for repeated task” – With Sass this can also mean extra outputted CSS. Which can lead to increased CSS file size. In the grand scheme of things may not seem to be that big of a deal but this can lead to extra bandwidth being used by end users, less performant websites, etc.
Example with output within a loop
Here we have a two font variables that we are generating helper classes for using a simple loop. Seems simple enough. But when you look at the output. It may simple obvious on what it may be – we get an output for each loop item.
Loop with placeholder and @extend
By utilising a couple more of Sass feature (yes we write more Sass for less CSS) we can update the code to reduce the complied CSS. By using Sass placeholder selectors and the @extend at-rule we can update the loop to just extend a placeholder. By default the Sass placeholder selector will not output itself, you have to use the @extend at-rule to. For each time you use the @extend inside a selector it reuses the placeholder styles and adds the selector to the list as shown below
With any pre-processors or tool you are using to generate the items you are serving to you end users.
You should, You must pay attention to the generated output. Something that may seem inconspicuous could turn out to be doing more than you expected.