Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 810311 of Synchronous and asynchronous requests

  • Revision slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
  • Revision title: Synchronous and asynchronous requests
  • Revision id: 810311
  • Created:
  • Creator: paul.irish
  • Is current revision? No
  • Comment sendbeacon to the rescue.

Revision Content

XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.

In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience. 

Asynchronous request

If you use XMLHttpRequest from an extension, you should use it asynchronously.  In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.

Example: send a file to the console log

This is the simplest usage of asynchronous XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null); 

Line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously.

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

Example: creating a standard function to read external files

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

function xhrSuccess () { this.callback.apply(this, this.arguments); }

function xhrError () { console.error(this.statusText); }

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var oReq = new XMLHttpRequest();
  oReq.callback = fCallback;
  oReq.arguments = Array.prototype.slice.call(arguments, 2);
  oReq.onload = xhrSuccess;
  oReq.onerror = xhrError;
  oReq.open("get", sURL, true);
  oReq.send(null);
}

Usage:

function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n\n");

Line 1 declares a function which will pass all arguments after the third to the callback function when the file has been loaded.

Line 4 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 5, and if it is, and the HTTP status is 200, calls the callback function.  If an error occurred, an error message is displayed.

Line 13 specifies true for its third parameter to indicate that the request should be handled asynchronously.

Line 14 actually initiates the request.

Example: using a timeout

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

  var args = arguments.slice(2);
  var xhr = new XMLHttpRequest();
  xhr.ontimeout = function () {
    console.error("The request for " + url + " timed out.");
  };
  xhr.onload = function() {
    if (xhr.readyState === 4) { 
      if (xhr.status === 200) {
        callback.apply(xhr, args);
      } else {
        console.error(xhr.statusText);
      }
    }
  };
  xhr.open("GET", url, true);
  xhr.timeout = timeout;
  xhr.send(null);
}

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

Usage:

function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", 2000, showMessage, "New message!\n");

Here, we're specifying a timeout of 2000 ms.

Note: Support for timeout was added in {{Gecko("12.0")}}.

Synchronous request

Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

Example: HTTP synchronous request

This example demonstrates how to make a simple synchronous request.

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

Example: Synchronous HTTP request from a Worker

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

example.html (the main page):

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
  var worker = new Worker("myTask.js");  
  worker.onmessage = function(event) {  
    alert("Worker said: " + event.data);
  };

  worker.postMessage("Hello");
</script>
</head>
<body></body>
</html>

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

Hello World!!

myTask.js (the Worker):

self.onmessage = function (event) {
  if (event.data === "Hello") {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "myFile.txt", false);  // synchronous request
    xhr.send(null);
    self.postMessage(xhr.responseText);
  }
};
Note: The effect, because of the use of the Worker, is however asynchronous.

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

Adapting Sync XHR usecases to the Beacon API

There are some few cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

See also

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

Revision Source

<p><code>XMLHttpRequest</code> supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.</p>

<p>In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience.&nbsp;</p>

<h2 id="Asynchronous_request">Asynchronous request</h2>

<p>If you use <code>XMLHttpRequest</code> from an extension, you should use it asynchronously.&nbsp; In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.</p>

<h3 id="Example.3A_send_a_file_to_the_console_log">Example: send a file to the console log</h3>

<p>This is the simplest usage of asynchronous <code>XMLHttpRequest</code>.</p>

<pre class="brush: js">
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
&nbsp; if (xhr.readyState === 4) {
&nbsp;&nbsp;&nbsp; if (xhr.status === 200) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; console.log(xhr.responseText);
&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; console.error(xhr.statusText);
&nbsp;&nbsp;&nbsp; }
&nbsp; }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null); </pre>

<p>Line 2 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p>

<p>Line 3 creates an event handler function object and assigns it to the request's <code>onload</code> attribute.&nbsp; This handler looks at the request's <code>readyState</code> to see if the transaction is complete in line 4, and if it is, and the HTTP&nbsp;status is 200, dumps the received content.&nbsp; If an error occurred, an error message is displayed.</p>

<p>Line 15 actually initiates the request.&nbsp; The callback routine is called whenever the state of the request changes.</p>

<h3 id="Example.3A_creating_a_standard_function_to_read_external_files">Example: creating a standard function to read external files</h3>

<p>In some cases you must read many external files. This is a standard function which uses the <code>XMLHttpRequest</code> object asynchronously in order to switch the content of the read file to a specified listener.</p>

<pre class="brush: js">
function xhrSuccess () { this.callback.apply(this, this.arguments); }

function xhrError () { console.error(this.statusText); }

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
&nbsp; var oReq = new XMLHttpRequest();
&nbsp; oReq.callback = fCallback;
&nbsp; oReq.arguments = Array.prototype.slice.call(arguments, 2);
&nbsp; oReq.onload = xhrSuccess;
&nbsp; oReq.onerror = xhrError;
&nbsp; oReq.open("get", sURL, true);
&nbsp; oReq.send(null);
}
</pre>

<p>Usage:</p>

<pre class="brush: js">
function showMessage (sMsg) {
&nbsp; alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n\n");
</pre>

<p>Line 1 declares a function which will pass all arguments after the third to the <font face="Courier New, Andale Mono, monospace"><span style="line-height:normal">callback&nbsp;</span></font>function when the file has been loaded.</p>

<p>Line 4 creates an event handler function object and assigns it to the request's <code>onload</code> attribute.&nbsp; This handler looks at the request's <code>readyState</code> to see if the transaction is complete in line 5, and if it is, and the HTTP&nbsp;status is 200, calls the callback function.&nbsp; If an error occurred, an error message is displayed.</p>

<p>Line 13 specifies <code>true</code> for its third parameter to indicate that the request should be handled asynchronously.</p>

<p>Line 14 actually initiates the request.</p>

<h3 id="Example.3A_using_a_timeout">Example: using a timeout</h3>

<p>You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the <code>timeout</code> property on the <code>XMLHttpRequest</code> object, as shown in the code below:</p>

<pre class="brush: js">
&nbsp; var args = arguments.slice(2);
  var xhr = new XMLHttpRequest();
  xhr.ontimeout = function () {
    console.error("The request for " + url + " timed out.");
  };
&nbsp; xhr.onload = function() {
&nbsp;&nbsp;&nbsp; if (xhr.readyState === 4) { 
&nbsp;&nbsp;&nbsp;   if (xhr.status === 200) {
&nbsp;&nbsp;&nbsp;     callback.apply(xhr, args);
&nbsp;&nbsp;&nbsp;   } else {
&nbsp;&nbsp;&nbsp;     console.error(xhr.statusText);
&nbsp;&nbsp;&nbsp;   }
&nbsp;&nbsp;&nbsp; }
&nbsp; };
&nbsp; xhr.open("GET", url, true);
  xhr.timeout = timeout;
&nbsp; xhr.send(null);
}
</pre>

<p>Notice the addition of code to handle the "timeout" event by setting the <code>ontimeout</code> handler.</p>

<p>Usage:</p>

<pre class="brush: js">
function showMessage (sMsg) {
&nbsp; alert(sMsg + this.responseText);
}

loadFile("message.txt", 2000, showMessage, "New message!\n");
</pre>

<p>Here, we're specifying a timeout of 2000 ms.</p>

<div class="note">
<p><strong>Note:</strong> Support for <code>timeout</code> was added in {{Gecko("12.0")}}.</p>
</div>

<h2 id="Synchronous_request">Synchronous request</h2>

<div class="note"><strong>Note:</strong> Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.</div>

<p>In rare cases, the use of a synchronous method is preferable to an asynchronous one.</p>

<h3 id="Example.3A_HTTP_synchronous_request">Example: HTTP synchronous request</h3>

<p>This example demonstrates how to make a simple synchronous request.</p>

<pre class="brush: js">
var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}
</pre>

<p>Line 3 sends the request.&nbsp; The <code>null</code> parameter indicates that no body content is needed for the <code>GET</code> request.</p>

<p>Line 5 checks the status code after the transaction is completed.&nbsp; If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.</p>

<h3 id="Example.3A_Synchronous_HTTP_request_from_a_Worker">Example: Synchronous HTTP request from a <code>Worker</code></h3>

<p>One of the few cases in which a synchronous request does not usually block execution is the use of <code>XMLHttpRequest</code> within a <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>.</p>

<p><code><strong>example.html</strong></code> (the main page):</p>

<pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDN Example&lt;/title&gt;
&lt;script type="text/javascript"&gt;
  var worker = new Worker("myTask.js"); &nbsp;
  worker.onmessage = function(event) { &nbsp;
&nbsp;   alert("Worker said: " + event.data);
  };

  worker.postMessage("Hello");
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;/html&gt;
</pre>

<p><code><strong>myFile.txt</strong></code> (the target of the synchronous <code><a href="/en/DOM/XMLHttpRequest" title="/en/XMLHttpRequest">XMLHttpRequest</a></code> invocation):</p>

<pre>
Hello World!!
</pre>

<p><code><strong>myTask.js</strong></code> (the <code><a href="/en/DOM/Worker" title="/en/DOM/Worker">Worker</a></code>):</p>

<pre class="brush: js">
self.onmessage = function (event) {
&nbsp; if (event.data === "Hello") {
&nbsp;&nbsp;&nbsp; var xhr = new XMLHttpRequest();
&nbsp;&nbsp;&nbsp; xhr.open("GET", "myFile.txt", false);  // synchronous request
&nbsp;&nbsp;&nbsp; xhr.send(null);
&nbsp;&nbsp;&nbsp; self.postMessage(xhr.responseText);
&nbsp; }
};
</pre>

<div class="note"><strong>Note:</strong> The effect, because of the use of the <code>Worker</code>, is however asynchronous.</div>

<p>It could be useful in order to interact in background with the server or to preload some content. See <a class="internal" href="/En/DOM/Using_web_workers" title="en/Using DOM workers">Using web workers</a> for examples and details.</p>

<h3 id="Irreplaceability_of_the_synchronous_use">Adapting Sync XHR usecases&nbsp;to the Beacon API</h3>

<p>There are some few cases in which the synchronous usage of XMLHttpRequest was not&nbsp;replaceable,&nbsp;like during the <a class="internal" href="/en/DOM/window.onunload" title="en/DOM/window.onunload"><code>window.onunload</code></a> and <a class="internal" href="/en/DOM/window.onbeforeunload" title="en/DOM/window.onbeforeunload"><code>window.onbeforeunload</code></a> events. &nbsp;The <a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> API can support these usecases typically while delivering a good UX.</p>

<p><span>The following example (from the <a href="/en-US/docs/Web/API/Navigator/sendBeacon">sendBeacon docs</a>)&nbsp;shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.</span></p>

<pre class="brush: js">
window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}
</pre>

<p>Using the <strong><code>sendBeacon()</code></strong> method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, <strong>without delaying the unload or affecting the performance of the next navigation.</strong></p>

<p>The following example shows a theoretical analytics code pattern that submits data to a server using the by using the <strong><code>sendBeacon()</code></strong> method.</p>

<pre class="brush: js">
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}
</pre>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a></li>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" title="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li>
 <li><a href="/en-US/docs/AJAX" title="/en-US/docs/AJAX">AJAX</a></li>
 <li><code><a href="/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a></code></li>
</ul>

<p>{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}</p>
Revert to this revision