简介
以下为各大浏览器并发请求限制的数量(只在同一与域名下有效)

可以看出主流浏览器请求并发数一般在2-8之间,这就可以解释下为什么把一些静态资源放在CDN上了,就是因为同域下并发请求有限制,这样就会造成请求阻塞,从而在一定程度上降低了页面渲染的速度,当然这只是部分原因哈,其他原因,比如请求头小,加载速度快等,在这里就不展开讲了。
回归正题,接下来,咱们以chrome浏览器为例,看下它的并发请求。
浏览器并发
为了演示效果,我在html同时加载10张图片,html如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<img src="http://localhost:8001/flx_bx/img/dir-small.png" alt="">
<img src="http://localhost:8001/flx_bx/img/bsl.png" alt="">
<img src="http://localhost:8001/flx_bx/img/excel.png" alt="">
<img src="http://localhost:8001/flx_bx/img/loading.gif" alt="">
<img src="http://localhost:8001/flx_bx/img/pic.png" alt="">
<img src="http://localhost:8001/flx_bx/img/video.png" alt="">
<img src="http://localhost:8001/flx_bx/img/s-loading.gif" alt="">
<img src="http://localhost:8001/flx_bx/img/dir-small1.png" alt="">
<img src="http://localhost:8001/flx_bx/img/menu_bgm.jpg" alt="">
<img src="http://localhost:8001/flx_bx/img/code.png" alt="">
</body>
</html>
很明显,可以看出这10张图片在同一域下,那么咱们看下浏览器是怎么加载的,如下图所示:

可以看到,浏览器只建立了6个连接,而其他请求则是pending状态,也就验证了浏览器并发限制是存在的,那么接下来,咱们就实现一个脚本,用于控制请求的并发。
控制并发
中心思想,就是当请求数大于指定的阀值时,将剩余请求存起来,等待有请求请求完毕后,再推出。
class RequestLimit {
constructor(options) {
this.unRequsetFn = [];
this.limit = options.limit || 2;
this.requestCount = 0;
}
async request(fn) {
if (this.requestCount >= this.limit) {
await new Promise((resolve) => this.unRequsetFn.push(resolve));
}
return this._handlerReq(fn);
}
async _handlerReq(fn) {
this.requestCount++;
try {
return await fn();
} catch (err) {
return Promise.reject(err);
} finally {
this.requestCount--;
if (this.unRequsetFn.length) {
this.unRequsetFn[0]();
this.unRequsetFn.shift();
}
}
}
}
这段代码主要就是利用async函数的await特性和Promise的状态,如果大于阀值就await,状态为pending,如果有请求执行完毕就推出一个,将状态置为Fulfilled。
那么测试下:
var requestLimit = new RequestLimit({ limit: 3 });
for (let i = 0; i < 8; i++) {
requestLimit.request(() =>
fetch(
"http://localhost:8001/flx_bx/img/dir-small.png"
)
);
}
效果如下图所示:

从瀑布图可以很明显的看出,请求并发数控制在3个了。
这里贴一个另外的解法,这个是看到一个大佬写的,链接在文章最后~
class TaskQuene {
constructor(concurrency) {
this.concurrency = concurrency;
this.running = 0;
this.quene = []; // 任务队列
this.results = [];
this.callback = null;
}
pushTask(task) {
this.quene.push(task);
this.next();
}
next() {
while (this.running < this.concurrency && this.quene.length) {
const task = this.quene.shift();
// 捕获请求返回值
task()
.then((resolve) => {
this.results.push({ resolve });
})
.catch((reason) => {
this.results.push({ reason });
})
.finally(() => {
this.running--;
this.next();
});
this.running++;
}
// 执行回调函数
if (typeof callback === "function" && this.running == 0) {
callback(this.results);
}
}
}
function sendRequest(urls, max, callback) {
// 简单的错误处理 urls 非数组抛错
if (!(urls instanceof Array) || urls.length === 0) {
throw Error(`urls`);
}
// 最大请求数目限制
if (!(max > 0)) {
max = urls.length;
}
// 定义一个任务队列
const downloadQueue = new TaskQuene(max);
downloadQueue.callback = callback;
urls.forEach((link) => {
let task = () => {
return fetch(link);
};
downloadQueue.pushTask(task);
});
}
1372

被折叠的 条评论
为什么被折叠?



