Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Reuse XMLHttpRequest object or create a new one?

I searched stackoverflow but got contradictory answers:

Why should I reuse XmlHttpRequest objects?

Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?

Also, there's a recommendation on w3schools.com :

If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.

Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You misunderstood W3School's recommendation. I'll highlight the relevant part:

If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.

It says that you use one AJAX function to fetch requests. This function will deal with the inconsistencies between IE and other browsers. XMLHttpRequest in standard-compliant browsers, and ActiveXObject in IE.

I recommend to use multiple XHR objects. With one global xhr object, your application can only deal with one request at a given time. It's also error-prone (eg. XMLHttpRequest launches multiple times without initiating the onreadystatechange function).

W3schools meant something like:

function createXHR() {
    try {
        return new XMLHttpRequest();
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
}
var xhr = createXHR();
xhr.open('get', '/test', true);
xhr.send();

Although it's better to create a function which handles requests, such as jQuery.ajax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...