简体   繁体   English

如果popper.js无法加载则回退

[英]Fallback if popper.js fails to load

How do I test that popper.js has loaded so that I can fallback from a CDN to a local copy? 如何测试popper.js是否已加载,以便我可以从CDN回退到本地副本?

Popper is required by Bootstrap 4 and must be loaded first. Bootstrap 4需要Popper,必须先加载。 I would like to use the same bootstrap fallback technique I use below so that if the popper.js CDN fails, the browser falls back to loading popper.js from my server. 我想使用下面使用的相同的bootstrap后备技术,以便如果popper.js CDN失败,浏览器将回退到从我的服务器加载popper.js。

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<script>if(typeof($.fn.modal) === 'undefined') {document.write('<script src="local/bootstrap.min.js"><\/script>')}</script>

Check the Popper variable. 检查Popper变量。

If its type is "undefined" then it Popper has failed to load and you can fallback to a local copy: 如果它的类型是“未定义”,则Popper无法加载,您可以回退到本地副本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script>if(typeof(Popper) === 'undefined') {document.write('<script src="static/lib/popper.min.js"><\/script>')}</script>

-- -

February 2019 Update 2019年2月更新

Since Chrome >55 now "intervenes" on some document.writes that include script tags (such as users on 2G mobile), but, if the document.write references the same domain or TLD+1 (ie, a script on static.mydomain.com referenced from a html file on www.mydomain.com), then Chrome won't intervene and stop the script download. 由于Chrome> 55现在“介入”某些包含脚本标记的文档(例如2G移动版用户),但是,如果document.write引用相同的域或TLD + 1(即static.mydomain上的脚本) .com从www.mydomain.com上的html文件引用,然后Chrome不会介入并停止脚本下载。 So for now the method above works fine. 所以现在上面的方法运行正常。 I've also evolved the code a little: 我还稍微改进了代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script>window.Popper || document.write('<script src="static/lib/popper.min.js"><\/script>')</script>

One other change to consider is to put the document.write here into a function and make an event call to your preferred analytics provider so that you can track when your site is falling back to a local copy of an external script, rather than it just silently doing so. 要考虑的另一个变化是将document.write置于函数中并向首选分析提供程序发出事件调用,以便您可以跟踪站点何时回退到外部脚本的本地副本,而不仅仅是默默地这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM