[英]How do I add the “crossorigin” tag to a dynamically loaded script?
Context: To quote the Mozilla documentation:上下文: 引用 Mozilla 文档:
Normal script tags will pass minimal information to the window.onerror for scripts which do not pass the standard CORS checks.
对于未通过标准 CORS 检查的脚本,普通脚本标签会将最少的信息传递给 window.onerror。 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.
为了允许对静态媒体使用单独域的站点进行错误记录,一些浏览器使用与标准 img crossorigin 属性相同的定义为脚本启用了 crossorigin 属性。
We realized our scripts were suffering from this issue ever since we moved our javascript to a CDN.我们意识到,自从我们将 javascript 移至 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.我们在脚本标签中添加了
crossorigin
属性,这对于“硬编码”脚本标签来说效果很好,但是我们动态加载了一些脚本,我不知道如何将crossorigin
标签添加到这些脚本中。
In Chrome 40: If I add a script tag dynamically using Javascript, like so:在 Chrome 40 中:如果我使用 Javascript 动态添加脚本标记,如下所示:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.crossorigin = 'anonymous';
script.src = some_url_on_another_domain;
head.appendChild(script);
I would expect for the crossorigin tag to get added to the script tag that gets inserted into my document.我希望将 crossorigin 标记添加到插入到我的文档中的脚本标记中。 However, when I examine the script tag in Developer tools, it is clearly not there.
但是,当我检查 Developer tools 中的 script 标签时,它显然不存在。 (And I can verify that the
origin
header is not being set in the request headers when requesting the script.) (并且我可以验证在请求脚本时未在请求标头中设置
origin
标头。)
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.现在,我改回对这些跨域脚本使用 ajax 请求,所以有解决方法,但现在我很好奇是否可以在动态脚本标签上添加 crossorigin 标签。
Well, I discovered my problem.嗯,我发现了我的问题。
This:这个:
script.crossorigin = 'anonymous';
should be this:应该是这样的:
script.crossOrigin = 'anonymous';
Note the capital "O" .注意大写的“O” 。 That attribute isn't capitalized in the HTML, but is capitalized in the JS interface.
该属性在 HTML 中没有大写,但在 JS 界面中大写。 Good to know!
很高兴知道!
Embarrassing, but I've decided to immortalize my mistake rather than delete the question in case someone else makes the same one.尴尬,但我决定让我的错误永垂不朽,而不是删除这个问题,以防其他人提出同样的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.