Phill Phill - 2 months ago 23x
Ajax Question

Prevent preflight OPTIONS when using sub domains

Given two sub domains:

Currently making any request from
results in the preflight OPTIONS request being made. This wouldn't be so much of an issue if it didn't add an extra 600ms to requests in China.

I was told that setting
document.domain = '';
in JS would resolve the issue but this hasn't helped at all.

Is it possible / how can I disable the OPTIONS request when sending to just a different sub domain.


Solved this using the iframe technique which seems to be what Facebook / Twitter do.

Steps below:

1) Set the document.domain to be the root domain. So given the url I set the domain in JavaScript like document.domain = '';

2) Setup an iframe which pulls a HTML file from the API Domain.

<iframe id="receiver" src="" style="position:absolute;left:-9999px"></iframe>

This is set to be positioned so it can't be seen.

3) Set the HTML of the receiver page to set the domain:

<!DOCTYPE html><body><script>document.domain=''</script></body></html>

4) Added an onload event to the iframe to capture the window once its loaded.


5) Assign the child window to a variable.

window.tempIframeCallback = function() {
  window.childWindow = window.receiver.contentWindow;

6) Make the XMLHttpRequest() from the childWindow instead of the main window.

var xhr = new window.childWindow.XMLHttpRequest();

Now all requests will be sent without a preflight OPTIONS request.

7) When using jQuery, you can also set the source of xhr in the settings:

  xhr: function() {
    return new window.childWindow.XMLHttpRequest();