With <script crossorigin='anonymous'>, why is a script “blocked by CORS policy”?


With Google Chrome or Firefox, if I try to load the following HTML:

<script crossorigin='anonymous' src='https://stackoverflow.com/foo.js'></script>

I get a CORS error like this:

Access to Script at 'https://stackoverflow.com/foo.js' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource...

However, the same tag without the crossorigin='anonymous' attribute works fine (of course generating a 404 error, since foo.js does not exist).

This is surprising, since anonymous is just supposed to prevent sending any credentials, and script tags are not supposed to require CORS. What is causing this, and what should I do?

I was confused about this for a while. Here's how I now understand it:

According to the W3C, there are actually three possible values for the crossorigin attribute: anonymous, use-credentials, and an "missing value default" that can only be accessed by omitting the attribute. (An empty string, on the other hand, maps to anonymous.) The default value causes the browser to skip CORS entirely, which is the normal behavior I was expecting.

The crossorigin attribute should only be used if we care about getting error information for the script being loaded. Since accessing this information requires a CORS check, the Access-Control-Allow-Origin header must be present on the resource for it to be loaded.


crossorigin attribute has only two possible values: anonymous or use-credentials. Any value other than anonymous, including empty value, will be translated to anonymous.

So these three tags have the same meaning:

<script src="https://stackoverflow.com/foo.js" crossorigin="anonymous">
<script src="https://stackoverflow.com/foo.js" crossorigin="">
<script src="https://stackoverflow.com/foo.js" crossorigin="IamCrazy">

What is interesting though, is that CORS behavior is totally disabled if you skip crossorigin attribute. For example:

<script src="https://stackoverflow.com/foo.js">

This tag will run script without any CORS-related checking. In practice, no crossorigin attribute makes browser skip Origin HTTP header entirely.

No matter if your crossorigin is anonymous or use-credentials, request's Origin must still match response's Access-Control-Allow-Origin. Otherwise no luck - script is never fired.

Source: HTTP access control (CORS) on Mozilla Developer Network


It's a bit old thread, but it's something that I happend to encauter, these days. In addition to the crossorigin, you should also make sure that the server from which you are loading the script (in your example - stackoverflow.com) returns a specific header.

'Access-Control-Allow-Origin' '*';

Only then you will be able to recieve the full information about an errors which has happend in the script.

Of course if you know for sure which url to allow you should use it instead of the asterix '*'.