原理:利用 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()會沒有效果。
查看本欄目