facebook为了提高用户体验,专门做了bigpipe这个前台渲染页面的框架。
开始以为就是通过将页面分成很多小块,然后发多个请求来进行渲染。
后来读了bigpipe-on-node这个nodejs插件介绍,才知道原来仅仅是在一个请求里面将各个模块进行分发。并且输出一部分就会发送一部分给浏览器,不会等待输出完毕之后发送给浏览器。
看了 Meteoric_cry 兄的文章之后,在他的基础上改了代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 var http = require('http'); 2 var sys = require('sys'); 3 var url = require("url"); 4 var down = 6; 5 http.createServer(function(request, response) { 6 7 response.writeHead(200, {"Content-Type" : "text/html"}); 8 response.write("<!Doctype html><html><head>"); 9 response.write("<style type='text/css'>div{border:2px solid #4F81BD; margin:30px; padding: 10px;}</style>"); 10 response.write("<script type=\"text/javascript\">function arrived(id,text) { var b=document.getElementById(id); b.innerHTML = text; }</script>"); 11 response.write("</head><body><div>Progressive Loading"); 12 for(var i = 0; i < 6; i++) { 13 response.write("<div id='" + i + "'>Loading...</div>"); 14 } 15 response.write("</div>"); 16 17 for (i = 0; i < 6; i++) 18 output(i, response, function (){ if(--down === 0) response.end();}) 19 response.write("</body></html>"); 20 21 }).listen(8080); 22 23 var output = function(id, response, callback) 24 { 25 var delay = Math.round(Math.random() * 8000); 26 setTimeout(function() { 27 var content = "<span>Content of Module " + id + "</span>"; 28 response.write("<script>" + 29 "arrived('" + id + "', '" + content + "');" + 30 "</script>"); 31 callback && callback(); 32 }, delay); 33 }