Search code examples
javascriptajaxasynchronousxmlhttprequestecmascript-5

Vanilla JavaScript async multiple xhr.open()


I would like know how to handle multiple xhr requests with vanilla JS. I want to open multiple html templates and load the page when all of them are ready. when I use few xhr.open() requests it will only return 1 template:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
    if(xhr.status === 200){
        storage.append(xhr.responseText);
    }
}
function getAsync(url) {
    xhr.open('get', url);
    xhr.send();
}
getAsync('localhost:3000/template1.html');
getAsync('localhost:3000/template2.html');

I understand that .open() only works 1 at a time. So is it possible to load all teamplates asynchronously or should I just load one after another in a synchronous matter? Also, I wonder,if I should create multiple xhr = new XMLHttpRequest() objects so that I could run multiple .open()?

Thank you


Solution

  • You are using one variable to define the xhr request, and using that variable twice, thus overriding the variable the second time. You need to create a loop and use let xhr; instead of var xhr as let has a block scope, so each instance in the loop will be independently defined.

    i.e. something like

    // Create iterable list of URLS
    let urls = ['localhost:3000/template1.html', 'localhost:3000/template2.html'];
    
    // Loop through URLs and perform request
    for(let i=0; i<urls.length; i++) {
        let xhr = new XMLHttpRequest();
    
        xhr.onload = function() {
            if(xhr.status === 200){
                storage.append(xhr.responseText);
            }
        }
    
        xhr.open('get', urls[i]);
        xhr.send();
    }