简体   繁体   中英

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 is required by Bootstrap 4 and must be loaded first. 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.

<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.

If its type is "undefined" then it Popper has failed to load and you can fallback to a local copy:

<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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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