【发布时间】:2020-06-18 13:08:22
【问题描述】:
在我们的网站上加载 JS SDK 时,我尝试了几种不同的方法。 我注意到 Snippet 1 导致 CORS 错误,而 Snippet 2 在 same page 上加载 same script 没有任何问题。
片段 1(使用 document.body.appendChild,引发 CORS 异常)
const url = 'https://www.example.com/sdk.js';
const scriptTag = document.createElement('script');
scriptTag.setAttribute('crossorigin', 'anonymous');
scriptTag.setAttribute('src', url);
document.body.appendChild(scriptTag);
片段 2(使用 parentNode.insertBefore,没有 CORS 异常)
const element = document.getElementsByTagName('script')[0];
const scriptTag = document.createElement('script');
scriptTag.async = !0;
scriptTag.crossorigin = 'anonymous';
scriptTag.src = 'https://www.example.com/sdk.js';
element.parentNode.insertBefore(scriptTag, element);
我试图找出每种情况的行为不同的原因,但找不到任何原因。
谁能指出我为什么会看到这种行为?
【问题讨论】:
-
我认为元素属性名称是“crossOrigin”,而不是“crossorigin”。
-
你是对的,刚刚用 scriptTag.crossOrigin = 'anonymous' 测试过,现在我得到了同样的行为。谢谢! ??????
标签: javascript dom browser