Optimize Your CSS With RequireJS
videos

Optimize Your CSS With RequireJS

Tutorial Details
  • Topic: CSS Optimization
  • Difficulty: Moderate

In this lesson, we’ll review the awesome RequireJS optimizer to handle the process of merging and compressing our stylesheets. While preprocessors continue to become increasingly popular, there are still plenty of folks who stick with regular CSS. In these cases, a solid build tool/process is vital.

Choose 720p for the clearest video.

Closing Thoughts

If you don’t like the idea of using Require.js, alternatively you might consider Grunt (along with the Grunt-CSS plugin), or Jake.

Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Andy

    Hey Jeff, Nice one ! Got a small doubt though. All of what you`ve shown in the video can be done using a css preprocessor (Eg: simpless, codekit) right ? Whats the advantage of using require over those preprocessors ? I didnt get the point.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Not everyone uses a preprocessor. Some smaller projects don’t really need them. I mention this at the end of the video. I tend to prefer command line tools.

  • LessLessMoreMore

    Gotta be honest. I just don’t agree with: “While preprocessors continue to become increasingly popular, there are still plenty of folks who stick with regular CSS. In these cases, a solid build tool/process is vital.” Even plain CSS is easy to keep track of, maintain, and expand. It’s just…easy. It’s not Java, Cobol, Perl, etc. Even when it’s 10 sheets and 1000s of lines, I’ve never had trouble working with it. It helps that I’ve been messing with CSS for well over a decade now, but still. I don’t get all this talk about needing to optimize and simplify CSS…the world’s easiest “language” that isn’t even a language.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Do you not merge your stylesheets for production?

    • Peter S.

      Sorry this is a bit off topic, but thinking that it’s fine to have your css source all in one file without concern for optimization is a rather shocking view.

      I wouldn’t agree that CSS is an easy language and considering that many projects involve people who are less experienced, it can be very beneficial to have them separate their concerns from yours.

      When you have a huge stylesheet an overall understanding of the styles from a glance is easily lost. Sure it’s easy to hack any solution for particular page or component, but if you want to reuse styles and understand and remember what sort of styles you have, it’s much easier to categorize and separate the files or chunks in some logical way.

      When you’re working by yourself on a project you know, it’s understandable you can understand what’s going on, but when someone comes from the outside it can easily look like chaos.

  • Bruno Gama

    Django Compressor does the job

  • Barry Wood

    What did you do to get the “tree” command in Terminal?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      brew install tree

  • http://inkwell.dotink.org Matthew J. Sahagian

    My CSS files are combined, compressed, and cached when I place them in the views of my framework, as is my JS. That being said, the question is what’s the proper balance of doing this vs. creating a bunch of unique files that contain 90% of the same content.

    It might make sense to combine, for example my reset and my primary stylesheet. But it doesn’t make sense to combine and cache my reset + primary stylesheet, which are used on every page along with the very page specific CSS files I might have. Let’s say I have 10 – 20 pages, each with some custom CSS outside of my reset and primary — well if I combine reset + primary + custom per page, then that means every page has it’s own “compiled” stylsheet, the vast majority of which is still the reset + primary. A single large HTTP request unique per page inevitably. It makes much more sense, instead to serve the smaller custom CSS files independent of this (still compressed, but not combined). This way, the much larger reset + primary CSS is browser cached, and the single HTTP request is only for the 20 – 40 lines of custom stuff per page.

    Combining all of them doesn’t necessarily make sense either though, cause the 20 – 40 lines per custom CSS for the 10 – 20 pages amounts to hundreds of additional CSS, which then is predominately not applicable to an individual page.

    In short, combine the big stuff that is common across all or a large number of pages. Keep smaller and unique stuff separate.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      I agree with your conclusion.

  • http://herozon.com Zarel

    What I love from Jeffrey is he can explain -the simple and the easy way- what thing are… how they are work… maybe that’s why they call him, Jeffrey Way!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Ahh, thanks. :)

  • http://www.google.com Rock

    Is somewhere tutorial about “right” or “good” workflow in site development, for example what to do, when i finished coding, how to compress and so on, to get better performance?

    • http://sideez.com Sideez

      I agree with Rock! Can we get a tutorial that explains best practices when moving from dev to production?

  • xifox

    HI, Jeff. Thanks for great tutorials! My question is. What is a terminal and color scheme in your tutorial?

  • RizerZero

    At a certain level it’s good to know the tools that can help you achieving your tasks so css preprocessor or Require JS it’s all your choice since you know now how to use theme , We are ready to learn anything with him no matter how hard it is that’s Why they Call him The MAN !

    awesome Jeffrey Way !

  • Rory

    Interesting to see how different people approach these things

    Currently I use Less Parser for Windows. It watches the diretory I’m working on, compresses the files and outputs the css. It understands imports too so you can segment your style sheets. So I’d keep a file for colours, grid structure etc that the main file reads and then uses when they’re referenced. You could use that for normal css too. You wouldn’t have to take advantage of the less way of developing.

    Then when it comes times to deploy I only move the css files as the rest are js.

    Interesting approach though.

  • 1234

    Is somewhere tutorial about “right” or “good” workflow in site development, for example what to do, when i finished coding, how to compress and so on, to get better performance?

  • Matt

    I know this is an old post, but I couldn’t resist adding my 2 cents in. I’ve tried using r.js, but to me it seems a big waste of time, for simply trimming down CSS. What I use, is a .php script, and a .htaccess rule (not required, but for esthetic purposes)

    .htaccess:

    RewriteRule ^css_min/(.*)$ css_min.php?file=$1 [L,NC]

    css_min.php:

    <?

    ob_start(“ob_gzhandler”);
    header(“Content-type: text/css; charset: UTF-8″);
    header(“Cache-control: must-revalidate”);
    $offset = 60 * 60;
    $expire = “Expires: ” . gmdate (“D, d M Y H:i:s”, time() + $offset) . ” GMT”;
    header($expire);

    $file = $_GET["file"];
    $fp = fopen($file, “r”);
    while(!feof($fp)) {
    $data = fgets($fp, 1024);
    $css .= $data;
    }
    fclose($fp);

    //echo “Before:”.mb_strlen($css);
    $css = preg_replace(“!/\*[^*]*\*+([^/][^*]*\*+)*/!”, “”, $css);
    $css = str_replace(array(“\r\n”, “\r”, “\n”, “\t”, ” “, ” “, ” “, ” “), “”, $css);
    $css = str_replace(‘; ‘, ‘;’, $css);
    $css = str_replace(‘: ‘, ‘:’, $css);
    $css = str_replace(‘, ‘, ‘,’, $css);
    $css = str_replace(‘ {‘, ‘{‘, $css);
    $css = str_replace(‘{ ‘, ‘{‘, $css);
    $css = str_replace(‘ }’, ‘}’, $css);
    $css = str_replace(‘} ‘, ‘}’, $css);
    echo $css;
    //echo “<br/>After:”.mb_strlen($css);

    ?>

    I know, it’s not the most elegant way to code a .php file, but it works, and I didn’t waste a lot of time writing the function.

    What this allows me to achieve, is to remove newlines, spaces etc, but most important of all – to compress the actual file itself using gzip. For example I have a style sheet right now that is 8.00 KB (8,192 bytes), and after the .css file runs through the css_min.php file, the size becomes 1.43 KB (1,461 bytes).

    In my opinion that’s a big improvement. And from my standpoint, as a developer, I can simply change the css include path to a compressed version or the original one, if I’d want to view the source from the browser (it happens sometimes), and because I cache the compressed version – it only runs once for a certain time frame. So no command lines, routine scripts or workarounds to compress my css files, it’s just a matter of pointing to /css/style.css or /css_min/style.css

    • Nitesh

      Matt are you kidding… what about those people who are not familiar with PHP stuff. works with js and css only???

  • http://www.ittrainingnepal.com Ittn

    It helped somewhat in optimizing CSS. Wish some other post about css optimization.

  • Jesus Bejarano

    Css is pretty ease to learn , the hard part is aplay it to your projects

  • http://iancrowther.co.uk Ian Crowther

    Hi,

    Have you looked at the h5bp node_build_script?

    https://github.com/h5bp/node-build-script

    It wraps grunt to build a sweet build chain. I am however waiting for yeoman.io. Im hoping that takes things a but further.

    Thanks

    Ian

  • http://www.facebook.com/lostnitesh Nitesh Pandey

    Good post. Seems lots more are required apart from RequireJS.. like linux or DOS etc :-)

  • fazthegreat

    Use Dojo with RequireJS, it’s awesome!