Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify HTML with CSS and Javascript?

I have a .html document with CSS and Javascript inside of document (no external files). Is there some online tool that would minify document and Javascript to some very small footprint? I saw many scripts kind of unreadable, where all variables and function names are replaced with one-letter names, etc. Please advice.

like image 693
Ωmega Avatar asked Jul 19 '12 20:07

Ωmega


1 Answers

Edit 2 (Feb 22, 2017): Now the best tool to minify your assets (and a whole lot more, by adding loaders and plugins) is definitely Webpack.

Example of config to move all your .css in one file and minify it:

{
  test: /\.css$/,
  use: [
    {
      loader: 'css-loader',
      options: {
        minimize: true
      }
    }
  ]
}

Edit 1 (Sept 16, 2014): Even better, now you have task runners like Gulp or Grunt.

Task runners are small applications that are used to automate many of the time consuming, boring (but very important) tasks that you have to do while developing a project. These include tasks such as running tests, concatenating files, minification, and CSS preprocessing. By simply creating a task file, you can instruct the task runner to automatically take care of just about any development task you can think of as you make changes to your files. It’s a very simple idea that will save you a lot of time and allow you to stay focused on development.

Must read: Getting started with Gulp.js

Example of task with JavaScript concatenation and minification (and JSHint):

gulp.task('scripts', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(notify({ message: 'Scripts task complete' }));
});

Original answer (Jul 19, 2012): I advise the HTML5 Boilerplate Build Script which can minify your JS and CSS.

like image 158
GG. Avatar answered Oct 01 '22 15:10

GG.