Reducing HTTP requests with Sass


Over time, whilst working on sites for several clients, I’ve built up a framework for CSS styles that I commonly use. To ease the front end dev, I would segregate these into separate stylesheets all imported by a styles.css file.


@import url("/_css/reset.css");
@import url("/_css/layout.css");
@import url("/_css/typography.css");
@import url("/_css/forms.css");
@import url("/_css/tables.css");
@import url("/_css/custom.css");
styles.css

Whilst this makes life much easier in developing and maintaining a site, it has a downside in the performance of the site as each @import results in an additional http request.

Recently I’ve started using the Sass CSS preprocessor for various reasons. One of these being that Sass provides a neat solution to the above problem with its use of partials. Here the @import is dealt with directly by Sass when compiling and saves you an http request whilst leaving you the partials to work with when developing and maintaining the site. The perfect solution! As an added bonus, you can configure SASS to minify the compiled CSS file it produces for you thus reducing the size of the remaining http request.

To do this, each of the imported files should be saved as a sass file (either .sass or .scss) with a leading underscore (e.g. _reset.scss). The leading underscore stops Sass from compiling these partials (as it would with any other Sass file in the watched folder). Then when you call these files you can omit the leading underscore and the file extension as below.


@import "partials/reset";
@import "partials/layout";
@import "partials/typography";
@import "partials/forms";
@import "partials/tables";
@import "partials/custom";
styles.scss

The partials are compiled into the file that imports them leaving us with a single styles.css file and no need for the CSS @import statements.

Further reading:


Leave a Reply

Your email address will not be published. Required fields are marked *