php 实现BigPipe分块输出

原理:利用 ob_flush()flush() 将缓冲区的内容提前输出,浏览器可提早加载这部分的内容,无需等待所有输出完成再加载。

将页面内容划分为一个个小块,输出一个后再输出下一个,使用户可尽早看到页面内容,优化用户体验。


首先 head 的内容应该优先加载,尽早加载css,javascript等静态内容,因此在head之后应该用 flush()输出。


例子:先输出head 静态内容,再将每个<p>分为一个chunk,每隔一秒输出。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title> Big Pipe </title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <style type="text/css">
  body{margin:0px; background:#CCCCCC;}
  p{text-align:center; margin:10px;}
  img{width:450px;}
  </style>
 </head>
 <?php cache_flush() ?>
 <body>  
  <p><img src="http://image.tianjimedia.com/uploadImages/2013/240/5CPOE4UZ2T40.jpg"></p>
  <?php cache_flush(); ?>
  <p><img src="http://image.tianjimedia.com/uploadImages/2013/240/6893CY9XEQD1.jpg"></p>
  <?php cache_flush(); ?>
  <p><img src="http://image.tianjimedia.com/uploadImages/2013/240/83H52SG02V32.jpg"></p>
 </body>
</html>
<?php
function cache_flush($sec=1){
    ob_flush();
    flush();
    usleep($sec*1000000);
}
?>

需要注意的问题:

1.尽量利用一次输出输出尽可能多的内容。
2.尽量可以同步加载。
3.chunk不是分得越多越好,要看实际需求情况决定。
4.ob_flush() 与 flush() 要同时使用,因有些情况flush()会没有效果。


posted @ 2013-09-15 12:33  傲雪星枫  阅读(284)  评论(0编辑  收藏  举报