开发者

Can I remove linebreaks and spaces from HTML source?

Besides the fact that it becomes unreadable for humans, are there any downsides when I remove every linebreak and space from the htm开发者_开发问答l source code?

Does the browsers render different then? Will the rendering get faster (or maybe slower)?


There are many already answered questions about minifying HTML. Here are some:

  • Why minify assets and not the markup?
  • HTML Minification
  • How to minify HTML code


You will have a smaller file size, so it may download faster (though it'll be probably unnoticeable). There are tools for this, indeed.


If you remove line breaks there is no harm. But according to your questions

...when I remove every linebreak and space from the html source code?

If you do remove every linebreak and line space, your purpose may not be served. You should only remove extra line-breaks and spaces. Also be careful not to alter values attributes form data, or any other attribute for that matter.

Regarding improvements it can offer:

It may render faster as it needs to parse lesser data. But this speedup is highly small. I even discourage it as it reduces readability and the speedup is in order of a few hundred clock cycles for CPU. The same goes for download. It reduces mere bites of data (unless the document has too much white spaces)

Insted of this its better to use GZIP compression for the output at the server side. The following is an line from php which enables it. If you have php in your server, then just rename your *.html file to *.php , Then add the following code before any output:

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");

you can also do this using the .htaccess file. Google regarding this more.


A bit late but still... By using output_buffering it is as simple as that:

function compress($string)
{
    // Remove html comments
    $string = preg_replace('/<!--.*-->/', '', $string);

    // Merge multiple spaces into one space
    $string = preg_replace('/\s+/', ' ', $string);   

    // Remove space between tags. Skip the following if
    // you want as it will also remove the space 
    // between <span>Hello</span> <span>World</span>.
    return preg_replace('/>\s+</', '><', $string);      
}

ob_start('compress');

// Here goes your html.    

ob_end_flush();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜