Are <script> tags subject to the same CORS restrictions as javascript/fetch calls?

Viewed 772

It's common practice to include scripts from other origins with script tags but when you use fetch calls on other origins then everything must be configured carefully other wise you will get a CORS error.

Does the script tag somehow bypass CORS? How does that work?

2 Answers

The Same Origin Policy prevents JavaScript reading data from other origins without permission (which is usually provided by CORS).

Running JavaScript from other origins is not prevented by the Same Origin Policy (nor is loading stylesheets, displaying images, content in iframes, etc).

JavaScript in the page can't (usually) read sensitive data from other origins through those methods in the first place.

It is noteworthy that if you switch to ES module way of loading Javascript (i.e. <script type="module" > ) then you need a CORS enabled server, if the src is on a different origin.

<!-- Not a CORS request -->
<script src="https://example.com/script.js"></script>

<!-- CORS request -->
<script type="module" src="https://example.com/script.js"></script>

you can find more here : https://jakearchibald.com/2021/cors/

Related