当我在我们的网站上加载JS SDK时,我尝试了几种不同的方法。我注意到代码片段1会导致CORS错误,而代码片段2可以在同一页面上加载相同的脚本而不会出现任何问题。
代码片段 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);
我试图找出每种情况行为不同的原因,但没有找到任何理由。
有人能指出为什么我会看到这种行为吗?