How do I add the “crossorigin” tag to a dynamically loaded script?

Context: To quote the Mozilla documentation:

Normal script tags will pass minimal information to the window.onerror
for scripts which do not pass the standard CORS checks. To allow error
logging for sites which use a separate domain for static media,
several browsers have enabled the crossorigin attribute for scripts
using the same definition as the standard img crossorigin attribute.

We realized our scripts were suffering from this issue ever since we moved our javascript to a CDN. We added the crossorigin attribute to our script tags, which works fine for the “hardcoded” script tags, but we load some scripts dynamically, and I can’t figure out how to add the crossorigin tag to these scripts.

In Chrome 40:
If I add a script tag dynamically using Javascript, like so:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.crossorigin = 'anonymous';
script.src = some_url_on_another_domain;

I would expect for the crossorigin tag to get added to the script tag that gets inserted into my document. However, when I examine the script tag in Developer tools, it is clearly not there. (And I can verify that the origin header is not being set in the request headers when requesting the script.)

For now, I am falling back to using ajax requests for these cross domain scripts instead, so there are workarounds, but now I am curious if it’s possible to add the crossorigin tag on dynamic script tags.

Well, I discovered my problem.


script.crossorigin = 'anonymous';

should be this:

script.crossOrigin = 'anonymous';

Note the capital “O”. That attribute isn’t capitalized in the HTML, but is capitalized in the JS interface. Good to know!

Read More:   Is there a function similar to setTimeout() (JavaScript) for PHP?

Embarrassing, but I’ve decided to immortalize my mistake rather than delete the question in case someone else makes the same one.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts