javascript - 如何将跨域添加到 <script> 标记?

标签 javascript jquery html html-lists

如何将跨域添加到以下 <script>标签?

目标是仅添加跨域,而不添加匿名或使用凭据属性。

当前输出:

<li><div id="somevalue"><script type="text/javascript" async src="some-source"></script></div></li>

期望的输出:

<li><div id="somevalue"><script type="text/javascript" crossorigin async src="some-source"></script></div></li>

(function() {
  var scriptTag = document.createElement('script');
  scriptTag.type="text/javascript";
  scriptTag.async=true;
  scriptTag.src="some-source";
  
  var divTag = document.createElement('div');
  divTag.id='somevalue';
  divTag.append(scriptTag);
  
  var liTag = document.createElement('li');
  liTag.append(divTag);
  
  var ulList = document.getElementById('footer-menu');
  ulList.append(liTag);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

最佳答案

只需使用 setAttribute :

(function() {
  var scriptTag = document.createElement('script');
  scriptTag.type="text/javascript"
  scriptTag.async=true
  scriptTag.setAttribute('crossorigin','anonymous')
  scriptTag.src="some-source";

  console.log(scriptTag);
})();

顺便说一句,crossorigin 属性并不意味着为空:https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes

关于javascript - 如何将跨域添加到 &lt;script&gt; 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420726/

相关文章:

javascript - 使用 jQuery、XML、JSON、JS 遍历表格

javascript - 具有 ID 属性的动态 DOM 对象的 IE9 内存泄漏

javascript - 为什么这段代码不运行?

jquery - XSLT 用于使用 javascript 过滤 XML 文档

jquery - 禁用动态创建的按钮

javascript - 不能在 Node/BabelJS 应用程序中使用装饰器

jquery - 加载后淡入带有背景图像的 Div

html - 如何在 React 中为 svg 图像添加颜色

html - 媒体查询无法正常工作

javascript - 如何随机翻转div