DarthVader
DarthVader

Reputation: 55022

Avoid CORS preflight OPTIONS for better performance

Working with a CDN provider and calling static HTML files from CDN like this.

          $.ajax({
            url : CDNPATH,
            type : "GET",
            contentType : "text/plain; charset=utf-8",
            async : async,
            cache : true,
            processData : false,
            success : function(response, status, xhr) {
                onSuccess(response, status, xhr);
                $(document).trigger('contentReady');
            }
        });

On the homepage of the application, I have 5 static HTML files which fires 5 OPTION calls. As you can imagine, it hurts the performance. I have seen on similar questions that it can be avoided with GET methods and text/plain, which I did as above but it didn't work.

How can I avoid these preflight OPTIONS methods?

Upvotes: 3

Views: 1806

Answers (1)

sideshowbarker
sideshowbarker

Reputation: 88056

Maybe the presence of the charset param is causing the preflight? Per-spec, browsers are required to ignore any params and only consider the MIME type, but maybe they’re not conforming.

A CORS-safelisted request-header is a header whose name is one of

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type and whose value, once parsed, has a MIME type (ignoring parameters) that is application/x-www-form-urlencoded, multipart/form-data, or text/plain

Elsewise I don’t see what in your request would trigger a preflight. Maybe I’m missing something…


Update 2017-02-20

OK based on information provided in a comment above it seems the source for the site contains a script element with this content:

window["_tsbp_"] = { ba : "X-TS-BP-Action", bh : "X-TS-AJAX-Request"};

…and I’ve not stepped through the rest of the code to see what effect that has, but it appears to be causing an X-TS-AJAX-Request header to get added to XHR requests, triggering the preflight.


I guess the general takeaway here is: whenever you find that a request is triggering a browser to do a preflight but you don’t know why, troubleshooting step number should probably be to use your browser devtools to find out exactly what request headers your code is causing to get sent out.

Upvotes: 3

Related Questions