原理:利用 ob_flush() 与 flush() 将缓冲区的内容提前输出,浏览器可提早加载这部分的内容,无需等待所有输出完成再加载。
将页面内容划分为一个个小块,输出一个后再输出下一个,使用户可尽早看到页面内容,优化用户体验。
首先 head 的内容应该优先加载,尽早加载css,javascript等静态内容,因此在head之后应该用 flush()输出。
例子:先输出head 静态内容,再将每个 分为一个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>@@##@@</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2373">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/176239923777053.png" alt="论小文">
</a>
<div class="aritcle_card_info">
<a href="/ai/2373">论小文</a>
<p>可靠的论文写作助手,包含11种学术写作类型,万字论文一键生成,可降重降AIGC,参考文献真实可标注,图表代码均可自定义添加。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="论小文">
<span>431</span>
</div>
</div>
<a href="/ai/2373" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="论小文">
</a>
</div>
<?php cache_flush(); ?>
<p>@@##@@</p>
<?php cache_flush(); ?>
<p>@@##@@</p>
</body>
</html>
<?php
function cache_flush($sec=1){
ob_flush();
flush();
usleep($sec*1000000);
}
?>需要注意的问题:
1.尽量利用一次输出输出尽可能多的内容。
2.尽量可以同步加载。
3.chunk不是分得越多越好,要看实际需求情况决定。
4.ob_flush() 与 flush() 要同时使用,因有些情况flush()会没有效果。
本篇文章讲解了如何通过php 实现BigPipe分块输出,更多相关内容请关注php中文网。
相关推荐:
以上就是如何通过php 实现BigPipe分块输出的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号