In web design, it is important that you minify or compress your HTML web page for a faster load. Google Page Speed includes “Minify HTML” as one of the factors that contribute to a fast loading web page.
Fortunately, you can do this easily with CodeIgniter using Hooks. Learn more about CodeIgniter Hooks.
In order to minify HTML output, we need to do the following steps:
- Enable hook on CodeIgniter:
- Open up/system/application/config/config.php.
- Set$config['enable_hooks'] = TRUE; - Create a hook file with the minify HTML:
- Create a fileMinifyhtml.phpin/system/application/hooks/folder.
- Copy paste the following code:
<?
class Minifyhtml {
function output()
{
$CI =& get_instance();
$buffer = $CI->output->get_output();$search = array(
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\',
'<', '\\1' );
$buffer = preg_replace($search, $replace, $buffer); $CI->output->set_output($buffer);
$CI->output->_display();
}
}
?>
Thanks to Jerome Jaglale at CodeIgniter Wiki for the Minify HTML code. - Setup your hook config file found at
/system/application/config/hooks.phpand enter the following code:
$hook['display_override'] = array(
'class' => 'Minifyhtml',
'function' => 'output',
'filename' => 'Minifyhtml.php',
'filepath' => 'hooks',
'params' => array()
);
The above code basically tells CodeIgniter to do a different thing for thedisplay_override(which is the hook to display the output). The code will tell CodeIgniter to find a file name calledMinifyhtml.phpin the folder/system/application/hooks/, find a classMinifyhtmland run the functionoutput()as a substitute when running thedisplay_override. Thus, it basically replaces the output with the minifyhtml function that we have created which takes in the output and produces the minified version.
There you go. A simple 5 minutes step that will help alot. Plus, if you don’t want to see the “minified” version of your HTML, you can simply turn the “hook” off in the config file.
