gpt4 book ai didi

javascript - CDN失败时不使用document.write()如何加载本地静态文件?

转载 作者:太空宇宙 更新时间:2023-11-04 15:45:07 25 4
gpt4 key购买 nike

我想要完成的事情


我将在 LAN 上为最多约 50 人托管一个 Web 应用程序。 LAN 之外的任何人都不会访问 Web 服务器。现在我有一个使用 CDN 的 Web 应用程序来提供 Bootstrap 和 jQuery 以及其他一些东西。我想让 Web 应用程序回退到 CDN 文件的本地静态副本,以防出现问题。


我的问题


  1. 如果我的 Web 服务器仅供 LAN 上的用户使用,哪种方法更好:CDN 还是本地文件?
  2. 如何使用document.write()回退到本地文件?

注意:我并不是只为 jQuery 尝试完成此操作。我想对多个文件执行此操作。


相关SO问题


我已经查看了几十个其他问题来回答我正在尝试做的事情,下面列出了最受欢迎的问题。

  1. Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
  2. How to load local script files as fallback in cases where CDN are blocked/unavailable?
  3. Is Google’s CDN for jQuery available in China?


我尝试过的


我从问题(1)中实现了以下代码

<!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>-->
<script>
console.log(window.jQuery) // ==> undefined
window.jQuery || document.write('<script type="text/javascript" src="{% static "js/jquery-3.4.1.min.js" %}"><\/script>');
console.log(window.jQuery) // ==> undefined
</script>

但是这个解决方案:

  1. 加载文档失败
  2. 使 Google Chrome DevTools 声明以下内容
[Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write
[Violation] Parser was blocked due to document.write(<script>)

这让我想到了标题为 A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it? 的 SO 问题.然后我尝试实现已接受的解决方案并将 async 附加到我的代码中,就像这样

<script>
console.log(window.jQuery) // ==> undefined
window.jQuery || document.write('<script type="text/javascript" src="{% static "js/jquery-3.4.1.min.js" %}" async><\/script>');
console.log(window.jQuery) // ==> undefined
</script>

但它仍然无法加载文档,我再次收到以下错误:

[Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write.


总结


那么实现这一目标的正确方法是什么?不使用 document.write() 如何做到这一点?似乎以前问题的答案现在已经过时了。

最佳答案

你应该监听onerror事件,如果它发生然后加载本地的。
这是一个示例(您应该更改代码以适合您的情况):

<script>
function onJqueryLoadError()
{
document.write('<scr' + 'ipt src="static/jquery-3.4.1.min.js"></scr' + 'ipt>');
}
</script>
<script src="https://www.cdn/jquery-3.4.1.min.js" onerror="onJqueryLoadError()"></script>

关于javascript - CDN失败时不使用document.write()如何加载本地静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56861425/

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