【发布时间】:2019-11-13 15:07:55
【问题描述】:
我想要完成的事情
我将在 LAN 上为最多 50 人托管一个 Web 应用程序。局域网外的任何人都不会访问 Web 服务器。现在,我的 Web 应用程序使用 CDN 来交付 Bootstrap 和 jQuery 以及其他一些东西。我想让 Web 应用程序回退到 CDN 文件的本地静态副本,以防出现问题。
我的问题
- 如果我的 Web 服务器仅由 LAN 上的用户使用,哪种方法更好:CDN 或本地文件?
- 如何不使用使用
document.write()回退到本地文件?
注意:我并不是只为 jQuery 来实现这一点。我想对几个文件执行此操作。
相关的 SO 问题
我查看了回答我正在尝试做的其他问题的几十个问题,下面列出了最受欢迎的问题。
- Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
- How to load local script files as fallback in cases where CDN are blocked/unavailable?
- 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>
但是这个解决方案:
- 加载文档失败
- 导致 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() 的情况下执行此操作?似乎以前问题的答案现在已经过时了。
【问题讨论】:
-
不要使用 CDN,如果它在 lan 上没关系,并且无论如何都会比任何 CDN 更快地提供服务:/
-
如果您已经有一个内部站点,为什么不在内部也托管这些库呢?这样您就不必担心外部 CDN 或尝试实施检查 CDN 脚本是否已加载的东西。
-
@Herohtar 我绝对可以这样做,我只是不确定是否应该使用 CDN。我只是将 CDN 用于开发目的,但现在我即将将其部署到生产环境中,我试图确保这个东西尽可能稳定(即不会中断并且有冗余),因此想要拥有后备计划。
-
对于内部的东西,CDN 并没有真正意义,尤其是对于少数用户而言。正如您已经意识到的那样,这使得站点依赖于外部资源。如果您在内部托管它们,那么只要您的内部服务器可用,就可以保证它们可用,并且如果您的内部服务器不工作,您网站的其他组件也将不可用。
标签: javascript jquery html twitter-bootstrap cdn