Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automatically minify my webpages?

Tags:

apache

minify

All of my .html and .php webpages should be minified. That means I would like to get all HTML-comments and more than one whitespace-character stripped.

Does an Apache-module exist for minification? (Or perhaps another method to automatically add a script directly before the output gets sent to the user?)

(I could add a function like the following, but if an Apache-module or another automatic solution existed, I could not forget to do so.)

<?
function sanitize_output($buffer)
{
    $search = array(
        '/\>[^\S ]+/s', //strip whitespaces after tags, except space
        '/[^\S ]+\</s', //strip whitespaces before tags, except space
        '/(\s)+/s'  // shorten multiple whitespace sequences
        );
    $replace = array(
        '>',
        '<',
        '\\1'
        );
  $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
}   
?>
like image 744
Martin Thoma Avatar asked Sep 30 '11 05:09

Martin Thoma


People also ask

How do I minify my website?

Go to minifycode.com and click the CSS minifier tab. Then paste the CSS code into the input box and click the Minify CSS button. After the new minified code is generated, copy the code. Then go back to the css file of your website and replace the code with the new minified version.

How do you minify HTML?

To minify HTML, try HTMLMinifier. To minify CSS, try CSSNano and csso. To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective.

Why would a website minify their source code?

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.


1 Answers

Try mod_pagespeed which may be of some use to you.

like image 81
shrikeh Avatar answered Oct 04 '22 20:10

shrikeh