Minify your CSS and JavaScript code!

If you are reading this article, you are probably somehow involved with web development. It is also most likely that you already know how search engines use page speed as one of the parameters for evaluating your site. We have couple of options on our disposal when it comes to increasing site speed. Today we will cover one of them.

Probably the simplest method of increasing site speed is minifying CSS and JavaScript. Even though this is pretty simple and straight forward method, for some reason, a lot of Magento stores and generally websites, don’t use this benefit. We have seen different cases where developers completely ignored code minification. Also, we have seen partially minified code. Partially means that, for example, theme code is minified but there is a lot of inline code which isn’t and it is possible to relocate and minify it. We’ve also seen cases where main theme code is minified but code from some other source (extension etc.) isn’t.

Before we go any further let us just ensure that we are on the same page about what “minified code” means. So, minified code is code without:

  • Whitespace characters
  • New line characters
  • Comments
  • Block delimiters.

Let us to suggest few possible options how to minify your code for production.

Minifying CSS and JavaScript code

In order to minify code we first need to decide are we going to do it manually or automatically. We’ll suggest to do automatically in order to speed up the development process, but if for some reason you want to do it manually, we don’t mind.

Do It Manually

CSS Minifying

If you are a developer who doesn’t use any kind of frontend “wizard” on your project (SASS, LESS, Gulp, Grunt etc.), the best option for you will be to use some kind of online or offline minifying tool. For example, one of the online minifying tools you can use is cssminifier.
If you are working on a complex project, you’re probably using some kind of IDE software. In that case you can speed things up by using some kind of IDE plugin that you can install or enable. That will minify the code every time when you save the working stylesheet file.

JavaScript Minifying

Very similar to minifying CSS code. There is bunch of online tools and different kind of IDE extensions for minifying JavaScript code. For example, good online tools are jscompress or javascript-minifier.

Do it automatically

This approach highly depends on the project and what we can or can’t change on it. Sometimes, it’s not possible to change the whole development environment just like that, especially if we’re collaborating with other developers on the same project. It’s not easy to suggest the best possible solution for everyone, but we’ll share what are we using on our Magento projects. We will assume that our audience is familiar with SASS, Compass, Gulp etc. If you need more information, please check out this article from my colleague. You can learn a lot of new things there.

SASS

If you already using SASS on your project, this will be easy for you. Just add additional parameter on sass –watch command:

sass --watch file.scss:file.css --style compressed

But, if you are not familiar with SASS then keep reading, maybe you will find even something better for you.

Compass

If project has Compass included, we already have Compass config file in the project. Just search for config.rb file, open the file and you should see something that looks something like the following:

# Require any additional compass plugins here.
 
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"
 
# You can select your preferred output style here (can be overridden via the command line):
output_style = :compressed # :expanded or :nested or :compact or :compressed
 
# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true
 
# To disable debugging comments that display the original location of your selectors. Uncomment:
line_comments = false

The config.rb file, Line 11 will likely be commented with the # sign. Uncomment the output_style (remove #). Then restart Compass to start watching for changes in SCSS files. To trigger it enter the command:

$ compass watch

Gulp

Gulp is a truly useful tool for better and faster frontend development. Here on Inchoo blog we have already mentioned few Gulp benefits. We often suggest using Gulp as one of the best tools for complex projects such as Magento frontend development itself.
With Gulp we have wide range of tools at our disposal which can be used to solve different kinds of development problems. But, currently we are only interested in code magnification tasks.

There is couple of ways to handle code magnification in Gulp, but we prefer these two Gulp tasks for that:

Minify CSS and JS code in Magento 1.x

If we take Magento 1.x for example, we need to handle with a lot of inline CSS and Javascript code inside template files. And in order to achieve the best possible results with code magnification, we need to take a look at your Magento template files and find all CSS and JavaScript code that we can transfer to our theme files. Keep in mind that in some cases we will not be in position to transfer all of them to appropriate theme files. Mostly in cases where JavaScript is depending on some php input/output.

Also, we suggest that while we’re transferring JavaScript code to theme file, we double check what code we need on which page. It is possible that we don’t need everything loaded on all Magneto pages. For example, some chunk of code is required just on the product page or just on the home page. That gives us possibility of splitting code in two different files which we can call on different occasions by using Magneto XML engine.

Let us create new gulp tasks which we will using for fast minifying code:

var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
 
// Css paths
var cssInput = '../sass/**/*.scss';
var cssOutput = '../css';
 
// script paths
var jsSkinInput = '../js/**/*.js';
var jsSkinOutput = '../js/';
 
// Js min task
gulp.task('skin-scripts', function() {
    return gulp.src(jsSkinInput)
        .pipe(uglify())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(jsSkinOutput));
});
 
// Sass task
gulp.task('sass', function () {
    return gulp.src(cssInput)
        .pipe(sass({
            errLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .pipe(gulp.dest(cssOutput))
});
 
// Sass file watcher
gulp.task('sass-watch', function() {
    return gulp
        .watch([cssInput, cssOutput], ['sass','browser-reload'])
        .on('change', function(event) {
            console.log('Css File ' + event.path + ' was ' + event.type + ', running tasks...');
        })
});
 
// Js file watcher
gulp.task('skin-scripts-watch', function() {
    return gulp
        .watch([jsSkinInput,jsSkinOutput], ['skin-scripts','browser-reload'])
        .on('change', function(event) {
            console.log('Js File ' + event.path + ' was ' + event.type + ', running tasks...');
        });
});
 
gulp.task('default', ['skin-scripts', 'skin-scripts-watch', 'sass', 'sass-watch']);

As we can see, we are watching for changes on all JavaScript and SASS files in our theme structure. Gulp recognized it and after few seconds Gulp generated minified code at the end. The first two task (skin-scripts and sass) are responsible for CSS and JavaScript minifying, and they work very similar, only difference being that JS files are renamed after minifying process by adding suffix .min at the end of file name. We wish to keep original file for further work and adjustments.

When you are ready, enter this command in your terminal in order to start Gulp tasks:

gulp default

Sounds simple right. But with Magento there’s always something additional 🙂

The thing is that Magento uses JavaScript not just in themes scope, but on the whole system. Major part of JavaScript which is responsible for keeping the system running is located in Magento root (js folder).

As we mentioned before, our goal is to have full minified JavaScript code. And we wish to do things properly. So we have two options:

First one is to adjust our Gulp task so that our task minifies root JavaScript code also, but that isn’t the best possible option. Why? Because with that action we will additionally complicate further maintenance and Magento upgrades. So, in order to avoid that, we want to minify root JavaScript code through Magento backend adjustments. Just before Magento JavaScript code merge.

The second option have been presented by my colleague Tomislav, check the article here.

Keep reading our blog and let us know what you think in the comments below 🙂