【问题标题】:How to load javascript from a CDN with a local fallback in the <head>如何在 <head> 中使用本地后备从 CDN 加载 javascript
【发布时间】:2012-07-20 17:05:49
【问题描述】:

我想使用Head JS 为我的页面动态加载所有其他脚本。我打算使用由CDNJS 托管的版本来利用更好的缓存、减少延迟等。

我没有理由认为 CDNJS 会走向任何地方,但即使对于像 jQuery 这样的 Google CDN 托管文件,我也喜欢包含一个后备。但是,当我使用 jQuery 时,这些文件包含在 &lt;body&gt; 标记的末尾。由于Head JS的性质,我需要将它包含在我页面的&lt;head&gt;中。

&lt;body&gt; 中,我会使用这样的两行代码:

<script src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.96/head.min.js"></script>
<script> window.head || document.write('<script src="js/libs/head-0.96.min.js"><\/script>') </script>

我可以在头部使用同一组行作为后备吗? document.write() 不会覆盖我的整个页面吗? &lt;head&gt; 中存在的脚本不会因为浏览器解析 DOM 的顺序而不同吗?

我对此还是很陌生,所以任何指导都会非常有帮助!谢谢!

【问题讨论】:

  • document.write 只有在页面加载完成后尝试这样做才会破坏您的文档。内联 document.write 将在页面加载/解析时执行,并将写入的数据按原样插入到文档中。
  • 是的,但是 ` 中的 Head JS 加载调用不会在 脚本从 document.write 加载之前触发吗?
  • 仅当您将前一个脚本标记标记为 async 时。否则同步加载脚本。

标签: javascript external cdn fallback head.js


【解决方案1】:

您可能已经知道,您不会测试 window.jQuery,而是测试 head.js 中包含的一些函数。

另外,你是对的,你可能不想在这里使用两次document.write()

不要使用document.write(),试试这个:

function appendScript(url) {
  var head = document.getElementsByTagName('head')[0];
  var theScript = document.createElement('script');
  theScript.type = 'text/javascript';
  theScript.src = url;
  theScript.onreadystatechange = callback;
  theScript.onload = callback;
  head.appendChild(theScript);
}

对于网址,请使用您的本地后备。

【讨论】:

  • 感谢您指出 jQuery 部分!我会试试这个!如何设置回调以在 Head JS 加载后运行 head.js() 命令?
  • 我不确定,我对 head.js 了解不多,但我不知道您是否可以保证它会按照设计在 head.js 之前或之后运行。
猜你喜欢
  • 2013-08-09
  • 1970-01-01
  • 2016-08-26
  • 2012-04-03
  • 2012-01-16
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
相关资源
最近更新 更多