【问题标题】:Dynamic loading of script shows different behaviour for same JS file脚本的动态加载显示相同 JS 文件的不同行为
【发布时间】: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


【解决方案1】:

我看到运行您的代码的唯一区别是@Pointy 在注释上指出的 on,第一个脚本生成:

<script crossorigin="anonymous" src="https://www.example.com/sdk.js"></script>

第二个:

<script async="" src="https://www.example.com/sdk.js"></script>

在我的控制台上运行,所以crossorigin 可能对 cors 错误负责。 (同样的事情发生在控制台上,顺便说一句)

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 2010-10-20
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多