三种思路:
1. WebSocket
2. 内嵌一个 iframe,写一个 timer 不停去刷新 iframe 中的内容(iframe 的 src 属性指向你的长耗时任务的 URL),根据内容字符串的最后一个百分号的值,获得进度。
3. 使用 ajax XMLHttpRequest level 2 API
给出一个例子:
后端:
```javascript
'use strict';
const http = require('http');
const server = http.createServer();
server.on('request', function(req, res) {
console.log('HTTP', req.method, req.url);
let n = 0;
res.writeHead(200, {
'Content-Type': 'text/plain',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Content-Length': 100
});
const inter = setInterval(function() {
res.write('.');
n++;
if (n >= 100) {
clearInterval(inter);
res.end();
}
}, 50);
res.on('error', function(err) {
console.log(err);
});
res.on('close', function() {
console.log('Connection close');
})
});
server.listen(8000);
```
前端:
```html
<!DOCTYPE html>
<HTML>
<head>
<meta charset="utf-8"/>
<style>
.progress-bar {
border: 1px solid rgb(230, 230, 230);
padding: 0px;
position: relative;
height: 4px;
border-radius: 2px;
}
.progress-bar > .progress-bar-inner {
margin: 0px;
width: 30%;
background-color: rgb(0, 180, 20);
height: 4px;
border-radius: 2px;
}
</style>
</head>
<body>
<div class="progress-bar">
<div id="pro" class="progress-bar-inner"></div>
</div>
<script src="
http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var progress = $('#pro');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8000/', true);
xhr.onprogress = function(event) {
if (event.lengthComputable) {
var pro = event.loaded/event.total;
console.log(pro);
progress.css('width', pro*100 + '%');
}
};
xhr.send();
</script>
</body>
</HTML>
```