您所指的网站正在使用速度 -
https://github.com/HubSpot/pace/
它监听所有 ajax 请求和 dom 加载,并在隐藏页面时显示进度条。加载完所有内容后,它会显示内容。
你可以预览这个库的一个例子here(是的,inception power)
来自 cmets 的更新:
您有 2 个帐户吗?
正如我已经所说,这个库做到了。它跟踪脚本本身之后加载的 EVERY 个字节。它易于自定义,并且有一个阅读的清晰文档。它允许您查看 dom 元素 加载进度、images/scripts/ajax 内容进度,甚至是您的长脚本。
如果您只有主要的 html 页面,那么您应该考虑更改您的设计并进行小块重构。
如果您不能并且仍想跟踪进度,您可以在页面顶部放置一个简单的脚本:
- 使用 ajax 为同一页面发送 HEAD http 请求。只是想知道您的总页面大小(Content-Length 标题)。
- 根据当前页面大小显示进度(多种跟踪方式,最简单的类似
document.firstElementChild.innerHTML.length(不会很精确))
- 加载页面后,移除进度条
我给了你一切你需要的东西。
编辑2:
我觉得你会要求更多...这是一个 NodeJs 示例。
它只是简单地创建一个 http 服务器,并提供一个带有分块内容的页面(并模拟滞后......)。所以整个页面需要时间来加载。
javascript实时显示文本进度。
var http = require('http');
function chunked(res, count) {
res.write('<p>Chunked content n°' + count + '</p>');
setTimeout(function() {
if(count > 0)
chunked(res, count - 1);
else
res.end('</body></html>');
}, 1000);
}
function handleRequest(request, response){
response.setHeader('Connection', 'Transfer-Encoding');
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.setHeader('Transfer-Encoding', 'chunked');
response.write('<html><head><script>\n' +
'var progress = 0; startLength = 825; TotalLength = 1090;\n' +
'function track_progress() {\n' +
' console.log(document.firstElementChild.innerHTML.length);' +
' if(progress > 1000) {' +
' document.body.firstElementChild.innerHTML = "Progress: 100% - Done !";\n' +
' return;\n' +
' }\n' +
' \n' +
' if(document.body) {\n' +
' progress = (document.firstElementChild.innerHTML.length - startLength)* 1000 / (TotalLength - startLength);\n'+
' document.body.firstElementChild.innerHTML = "Progress: " + (Math.round(progress)/10) + "%";\n' +
' }\n' +
' setTimeout(track_progress, 500);\n' +
'}\n' +
'track_progress();\n' +
'</script></head><body><p id="progress">Progress: 0%</p>');
response.write('<p>Starting to send chunked content...</p>');
chunked(response, 10);
}
var server = http.createServer(handleRequest);
server.listen(8080, function(){
console.log("Server listening on: http://localhost:8080");
});