Among the best practices to be up when optimizing load time of pages of a website is regularly speaks of the "minification" HTML, CSS and JavaScript.
Behind this barbarous word hides a very simple technique: it is to compress a file up to reduce its weight. To do this, remove all code comments, line breaks and unnecessary spaces in the file.
For minify our files easily, there are several WordPress plugins like WP Minify or W3 Total Cache.
Yet with a few lines of code, it is possible to optimize the weight of our files without plugin. For example, to reduce the weight of HTML files from a WordPress theme, copy the following code in the functions.php file at the root of your theme:
- add_action('get_header', 'gkp_html_minify_start');
- function gkp_html_minify_start() {
- ob_start( 'gkp_html_minyfy_finish' );
- }
- function gkp_html_minyfy_finish( $html ) {
- // Suppression des commentaires HTML,
- // sauf les commentaires conditionnels pour IE
- $html = preg_replace('/<!--(?!s*(?:[if [^]]+]|!|>))(?:(?!-->).)*-->/s', '', $html);
- // Suppression des espaces vides
- $html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
- while ( stristr($html, ' '))
- $html = str_replace(' ', ' ', $html);
- return $html;
- }
Similar Article : 10 tips for choosing a WordPress plugin
Minify HTML files to a WordPress site without plugin
Reviewed by Nicole
on
March 04, 2015
Rating:
Hello I tried this script with wordpress. It seemed to work fine. However one thing I noticed is that all my pre and code tags stopped working. All code was with a scroll bar inline. No css styling help. When I disabled your script it all went back to normal
ReplyDeleteHi Daniel, then you Better use these two Plugin's : WP Minify or W3 Total Cache.
DeleteI was hoping to do it without a plugin. I thought maybe it had to do with the regular expression used but I really am bad at regular expressions.
ReplyDeleteThank you
Would it have something to do with a possible typo in this:
ReplyDelete"gkp_html_minyfy_finish"