gpt4 book ai didi

javascript - 如何使用 中的本地回退从 CDN 加载 javascript

转载 作者:数据小太阳 更新时间:2023-10-29 05:39:01 24 4
gpt4 key购买 nike

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

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

<body>我会使用这样的两行:

<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()覆盖我的整个页面?当脚本存在于 <head> 中时,它们的加载方式是否不同?由于浏览器解析 DOM 的顺序?

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

最佳答案

您可能已经知道,您不会测试 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);
}

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

关于javascript - 如何使用 <head> 中的本地回退从 CDN 加载 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com