压缩HTML 保留textarea pre

如何提高网页加载速度 需要怎么对HTML页面优化

清除注释标记 换行符 空格 制表符等
减小HTML页面体积来提高前端加载速度

启用gzip的话每次请求都需要压缩 会比较消耗服务器资源
对JS CSS启动gzip比较好是因为JS CSS都会使用缓存

使用PHP压缩HTML注意事项
使用PHP来压缩HTML实现的方式主要是用正则表达式去查找 替换 在HTML压缩的时候 主要要注意下面几点:


HTML中的pre textarea标签里面的任何空白 都不能被删除
因此pre textarea标签里面的内容格式需要保留 不能压缩

HTML中有可能有IE条件注释 这些条件注释是文档逻辑的一部分 不能被删除
因此去掉HTML注释的时候 有些注释是不能去掉的 比如:<!--[if lt IE9]> <![endif]-->
压缩嵌入式JS中的注释要注意 因为可能注释符号会出现在字符串中
如 var url = "http://www.94qing.com"; // 前面的//不是注释
对于动态页面来说 HTML的压缩有可能还会增加服务器的CPU负担 得不偿失

PHP压缩HTML函数
特殊情况下可以使用<!--<nocompress>--><!--</nocompress>-->或者<nocompress></nocompress>来指定不压缩的代码
pre textarea标签不压缩
特别对JS的单行注释做出优化



function qlwz_compress_html($html_source){
$chunks   = preg_split('/(<!--<nocompress>-->.*?<!--<\/nocompress>-->|<nocompress>.*?<\/nocompress>|<pre.*?\/pre>|<textarea.*?\/textarea>|<script.*?\/script>)/msi', $html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
$compress = '';
foreach ($chunks as $c) {
  if (strtolower(substr($c, 0, 19)) == '<!--<nocompress>-->') {
      $c = substr($c, 19, strlen($c) - 19 - 20);
      $compress .= $c;
      continue;
  } elseif (strtolower(substr($c, 0, 12)) == '<nocompress>') {
      $c = substr($c, 12, strlen($c) - 12 - 13);
      $compress .= $c;
      continue;
  } elseif (strtolower(substr($c, 0, 4)) == '<pre' || strtolower(substr($c, 0, 9)) == '<textarea') {
      $compress .= $c;
      continue;
  } elseif (strtolower(substr($c, 0, 7)) == '<script' && strpos($c, '//') != false && (strpos($c, "\r") !== false || strpos($c, "\n") !== false)) { // JS代码 包含“//”注释的 单行代码不处理
      $tmps = preg_split('/(\r|\n)/ms', $c, -1, PREG_SPLIT_NO_EMPTY);
      $c    = '';
      foreach ($tmps as $tmp) {
          if (strpos($tmp, '//') !== false) { // 对含有“//”的行做处理
              if (substr(trim($tmp), 0, 2) == '//') { // 开头是“//”的就是注释
                  continue;
              }
              $chars   = preg_split('//', $tmp, -1, PREG_SPLIT_NO_EMPTY);
              $is_quot = $is_apos = false;
              foreach ($chars as $key => $char) {
                  if ($char == '"' && !$is_apos && $key > 0 && $chars[$key - 1] != '\\') {
                      $is_quot = !$is_quot;
                  } elseif ($char == '\'' && !$is_quot && $key > 0 && $chars[$key - 1] != '\\') {
                      $is_apos = !$is_apos;
                  } elseif ($char == '/' && $chars[$key + 1] == '/' && !$is_quot && !$is_apos) {
                      $tmp = substr($tmp, 0, $key); // 不是字符串内的就是注释
                      break;
                  }
              }
          }
          $c .= $tmp;
      }
  }

  $c = preg_replace('/[\\n\\r\\t]+/', ' ', $c); // 清除换行符 清除制表符
  $c = preg_replace('/\\s{2,}/', ' ', $c); // 清除额外的空格
  $c = preg_replace('/>\\s</', '> <', $c); // 清除标签间的空格
  $c = preg_replace('/\\/\\*.*?\\*\\//i', '', $c); // 清除 CSS & JS 的注释
  $c = preg_replace('/<!--[^!]*-->/', '', $c); // 清除 HTML 的注释
  $compress .= $c;
}
return $compress;
}