Clean your HTML output
Sometimes you'd like to clean your HTML output to remove useless stuff that may slow down the loading of your page. Here is a little trick to slim your website output ;)
Let's say we want to remove comments, lines separator (that can affect the loading of your page) and blank spaces. All we have to do is to collect all the output returned by cake, modify it and return it in the afterFilter hook in the app_controller.php file:
You can check out the results on my website http://www.lescigales.org, enjoy ;)
Controller Class:
Download code
<?php
class AppController extends Controller
{
function beforeRender()
{
if (Configure::read('debug') == 0) {
ob_start();
}
}
function afterFilter()
{
if (Configure::read('debug') == 0) {
$output = ob_get_contents();
ob_end_clean();
echo $this->_clean($output);
}
}
function _clean($string)
{
$string = str_replace("\n", '', $string);
$string = str_replace("\t", '', $string);
$string = preg_replace('/[ ]+/', ' ', $string);
$string = preg_replace('/<!--[^-]*-->/', '', $string);
return $string;
}
}
?>
You can check out the results on my website http://www.lescigales.org, enjoy ;)
Comments
Comment
1 Nice Idea but
Also, as for increasing performance, I would have thought that running the entire output through 2 preg_replace()'s would actually slow things down a bit (unless CakePHP is caching the output - did you try benching this?)
Comment
2 Nice Idea but
No I didn't benchmark these 2 preg_replace() as Im not focused on micro-optimization and as this article was more about the functionality first :)
Some time ago someone suggested me a more elegant way to achieve this, with a component I believe.
Thanks for your comment !