Jul 3, 2013

Magento: How to minified your html content?

I know its very bad idea to modify the core code, but sorry I don't have time to test override the class.


To do this you need to modify Mage_Core_Block_Template class and its fetchView method.

public function fetchView($fileName)
{
  // ***********
  // Some other code up
  // *********************

  // This is the in the bottom code
  if (Mage::app()->getStore()->getCode() == 'admin'){
     // Admin must not to minify since, there was lot on inline comment(//)
     // which generate javascript error.
     return $html;
  }else{
    // Instead of just returning the html data, you need to
    //  remove the  un-needed extra space and new lines.
    $html = preg_replace('/\s+/', ' ', trim($html)); // remove new line

    // Remove space on every start on a tag </script> <div> become </script> <div>
    $html = preg_replace('/ </', '<',$html); // For more compression only you can skip this line.

    return $html; 
  }


}







WARNING:

This is not applicable if you have javascript in your template will an inline comment double slash(//). Since the code become one line, whole javascript after the // become comment. I know you know that. Suggestion pleas use the group comment(/*** Your comment inside */) or move all you javascript in a js file. :)

Cheerr

No comments: