How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

后端 未结 8 1357
无人共我
无人共我 2020-11-21 11:37

In Firefox 3, the answer is 6 per domain: as soon as a 7th XmlHttpRequest (on any tab) to the same domain is fired, it is queued until one of the other 6 finish.

Wha

8条回答
  •  青春惊慌失措
    2020-11-21 11:57

    Wrote my own test. tested the code on stackoverflow, works fine tells me that chrome/FF can do 6

    var change = 0;
    var simultanius = 0;
    var que = 20; // number of tests
    
    Array(que).join(0).split(0).forEach(function(a,i){
        var xhr = new XMLHttpRequest;
        xhr.open("GET", "/?"+i); // cacheBust
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 2){
                change++;
                simultanius = Math.max(simultanius, change);
            }
            if(xhr.readyState == 4){
                change--;
                que--;
                if(!que){
                    console.log(simultanius);
                }
            }
        };
        xhr.send();
    });
    

    it works for most websites that can trigger readystate change event at different times. (aka: flushing)

    I notice on my node.js server that i had to output at least 1025 bytes to trigger the event/flush. otherwise the events would just trigger all three state at once when the request is complete so here is my backend:

    var app = require('express')();
    
    app.get("/", function(req,res) {
        res.write(Array(1025).join("a"));
        setTimeout(function() {
            res.end("a");
        },500);
    });
    
    app.listen(80);
    

    Update

    I notice that You can now have up to 2x request if you are using both xhr and fetch api at the same time

    var change = 0;
    var simultanius = 0;
    var que = 30; // number of tests
    
    Array(que).join(0).split(0).forEach(function(a,i){
        fetch("/?b"+i).then(r => {
            change++;
            simultanius = Math.max(simultanius, change);
            return r.text()
        }).then(r => {
            change--;
            que--;
            if(!que){
                console.log(simultanius);
            }
        });
    });
    
    Array(que).join(0).split(0).forEach(function(a,i){
        var xhr = new XMLHttpRequest;
        xhr.open("GET", "/?a"+i); // cacheBust
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 2){
                change++;
                simultanius = Math.max(simultanius, change);
            }
            if(xhr.readyState == 4){
                change--;
                que--;
                if(!que){
                    document.body.innerHTML = simultanius;
                }
            }
        };
        xhr.send();
    });

提交回复
热议问题