UPUPD技术论坛

标题: WordPress优化加速:前端代码压缩教程 [打印本页]

作者: 洛尘    时间: 2015-4-29 16:27
标题: WordPress优化加速:前端代码压缩教程
教程介绍
使用代码方法实现WordPress前端代码压缩,压缩页面的好处就是减少了页面的体积,从访问速度上来说,更快些,尽管这些是很难感觉出来的,但是当你流量大了就能有感觉了,这样还可以给扒皮的用户制造麻烦让他一看你源代码就想关闭!
代码预览
将以下代码放到当前使用主题的functions.php文件即可,不过由于代码比较多个人还是推荐单独创建一个PHP文件然后在functions.php文件里面调用即可。比如创建一个cleloo.com.php文件将以下代码复制进去,然后上传到当前使用的主题文件夹里面,然后在functions.php文件里面添加一段include(‘cleloo.com.php’);代码进行调用
  1. // html代码压缩
  2. <?php
  3. function wp_compress_html()
  4. {

  5. function wp_compress_html_main ($buffer)
  6. {
  7. $initial=strlen($buffer);
  8. $buffer=explode("<!--wp-compress-html-->", $buffer);
  9. $count=count ($buffer);

  10. for ($i = 0; $i <= $count; $i++)
  11. {
  12. if (stristr($buffer[$i], '<!--wp-compress-html no compression-->'))
  13. {
  14. $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->", " ", $buffer[$i]));
  15. }
  16. else
  17. {
  18. $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
  19. $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
  20. $buffer[$i]=(str_replace("\n", "", $buffer[$i]));
  21. $buffer[$i]=(str_replace("\r", "", $buffer[$i]));

  22. while (stristr($buffer[$i], ' '))
  23. {
  24. $buffer[$i]=(str_replace(" ", " ", $buffer[$i]));
  25. }
  26. }
  27. $buffer_out.=$buffer[$i];
  28. }
  29. //$final=strlen($buffer_out);
  30. //$savings=($initial-$final)/$initial*100;
  31. //$savings=round($savings, 2);
  32. //$buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
  33. return $buffer_out;
  34. }
  35. ob_start("wp_compress_html_main");
  36. }
  37. add_action('get_header', 'wp_compress_html');
  38. ?>
复制代码

如果压缩后的页面某些地方出问题了可以用以下代码添加到对应文件来解决,如果你不会建议不要使用该教程
  1. <!--wp-compress-html--><!--wp-compress-html no compression-->
  2. 不被压缩的部分
  3. <!--wp-compress-html no compression--><!--wp-compress-html-->
复制代码








欢迎光临 UPUPD技术论坛 (http://bbs.upupd.com/) Powered by Discuz! X3.2