BigPipe笔记

来源:互联网 发布:易推客营销软件下载 编辑:程序博客网 时间:2024/05/29 10:49
BigPipe是一种提高网页响应速度的技术。


先上例子:
<?php /* big pipe demo */ ?>
<!DOCTYPE html>
<html>
  <head>
    <title>BigPipe Demo 3</title>
    <script>
      function render(pageletId,html){
        document.getElementById(pageletId).innerHTML=html;
      }
    </script>
  </head>
  <body>
    <div id='header'><p>Loading…</p></div>
    <div id='content'><p>Loading…</p></div>
    <div id='footer'><p>Loading…</p></div>
  </body>
  <?php
     ob_start();
     ob_flush();
     flush();
     sleep(1);
     $header = str_pad('<span>111111</span>', 4096);
     ?>
  <script>render('header', "<p><?php echo $header;?><p>");</script>
  <?php
     ob_flush();
     flush();
     sleep(1);
     $content = str_pad('<span>222222</span>', 4096);
     ?>
  <script>render('content', "<p><?php echo $content;?><p>");</script>
  <?php
     ob_flush();
     flush();
     sleep(1);
     $footer = str_pad('<span>333333</span>', 4096);
     ?>
  <script>render('content', "<p><?php echo $content;?><p>");</script>
  <?php
     ob_flush();
     flush();
     sleep(1);
     $footer = str_pad('<span>333333</span>', 4096);
     ?>
  <script>render('footer', "<p><?php echo $footer;?><p>");</script>
  <?php
     ob_flush();
     flush();
     ?>
</html>


配置:
php.ini中的output_buffering要设置成4096。如果使用的网页服务器是Nginx,需要关闭gzip和fastcgi_buffers。fastcgi_buffers通常配置在文件conf/fastcgi_params中,通过include在nginx.conf中引用。
 
解释:
  使用ob_flush、flush和str_pad三个函数,是为了将当前已经渲染的页面发送到浏览器。没有采用Big pipe技术时,页面是全部生成完毕后,再发送到浏览器端。浏览器端只有一次渲染。而采用Big pipe技术时,页面被拆分成多个小块,然后像流一样传送到浏览器的。服务器生成一块页面就发送一块,浏览器也会有多次渲染,浏览器收到一块页面就渲染一块。页面总的加载时间没有变化,但是浏览器开始渲染的时间提前,用户体验更好。而且和采用Ajax的方式相比,Big pipe只有一次tcp连接,编码复杂度也很低。Big pipe的流程大概是:
     服务器             浏览器            用户
  生成页面块1  --->  渲染页面块1  --->  浏览页面块1
  生成页面块2  --->  渲染页面块2  --->  浏览页面块2
  生成页面块3  --->  渲染页面块3  --->  浏览页面块3
 
使用的函数:
  bool ob_start([callback $output_callback[, int $chunk_size[, bool $erase]]])
  打开output buffer。当output buffer是打开的,php不会发送数据,而是写到output buffer中。
 
  void ob_flush(void);
  将output buffer中的数据发送出去。手动使用ob_flush、flush和str_pad,是为了在输出页面时,保证输出的一个完成的html标签。如果由php管理缓存的刷新,可能出现输出不完整的html标签,导致页面和最终页面(全部加载完毕)的不一样。
 
  void flush(void);
  刷新php的write buffers。
 
  string str_pad(string $input, int $pad_length[, string $pad_string = ""[, int $pad_type = STR_PAD_RIGHT]]);
  是用指定字符填充字符串。使用时pad_length应该和output_buffering的设置一致。
 
参考: 
http://huoding.com/2011/06/26/88
http://www.alibuybuy.com/posts/66345.html
http://www.oschina.net/p/bigpipe/similar_projects
http://www.cnblogs.com/mofish/archive/2011/11/03/2234858.html
 
0 0
原创粉丝点击