cssless

Benefit of stated @import vs. compiled @import in CSS


I'm using WinLESS, a LESS compiler for Windows. In style.less, I'm using @import directives to import my 768up.less and 1030up.less, etc.

The compiled style.css has the contents of 768up.less and 1030up.less parsed inline, for example:

style.less

@import "normalize.less";
/* base styling here */
@media only screen and (min-width: 768px) { @import "768up.less"; }
@media only screen and (min-width: 1030px) { @import "1030up.less"; }

style.css

/* imported normalize */
html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } /* etc */

/* base styling */
.wrap { margin: 0; padding: 0 5px; } /* etc */

/* imported 768up */
.wrap { padding: 0 20px; }

/* imported 1030up */
.wrap { padding: 0 30px; }

Doesn't this defeat the purpose of the @import which are mixed with @media? I mean, the filesize of style.css is now the sum of all imported + compiled files.

Even if the browser won't use 1030up because of small screen size, will it still have downloaded style.css in its entirety?

Isn't the compiled style.css supposed to contain the @import directives unchanged, so that style.css becomes more lightweight and simply instructs to browser to retrieve additional styling if the @media criteria is met?

Is WinLESS compiling these CSS files wrong for me?

Ideally, I'd like to see the following:

/* normalize */
@import "normalize.css";

/* base styling */
.wrap { margin: 0; padding: 0 5px; } /* etc */

/* progressively enhance styling to accomodate larger screens */
@media only screen and (min-width: 768px) { @import "768up.css"; }
@media only screen and (min-width: 1030px) { @import "1030up.css"; }

Please, if I'm misunderstanding the whole concept of @import, enlighten me!


Solution

  • Reducing round trips generally improves performance more than reducing sizes.

    It's the same idea as using sprite sheets. Making 4 requests for 1kb is a lot worse than making 1 request for 20kb.

    In this case, it can't even do the requests concurrently. It must get the first file, parse it, and only then does it realize it must go back to the server to get another file.

    Also mind how gzip works. 1kb+1kb != 2kb.

    If you suspect you're in a case where you'd rather keep the files split, LESS only inline includes @import if it's a .less, so try:

    @media only screen and (min-width: 768px) { @import "768up.css"; }
    @media only screen and (min-width: 1030px) { @import "1030up.css"; }
    

    (note the .css instead of the .less)

    More details can be found by doing a control+f, search for "Importing" on http://lesscss.org/

    You can enforce the import type it's doing like:

    @import (css) "foo.bar";
    @import (less) "foo.bar";