Javascript 如何在不使用document.write()的情况下为CDN库创建回退

Javascript 如何在不使用document.write()的情况下为CDN库创建回退,javascript,html,cdn,fallback,Javascript,Html,Cdn,Fallback,我想包括来自CDN的第三方库,比如jQuery。我还想创建一个后备方案,以便在CDN失败时,包括我自己的本地副本。我采纳了以下建议: 这就是我在页面中包含jQuery的方式: <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="

我想包括来自CDN的第三方库,比如jQuery。我还想创建一个后备方案,以便在CDN失败时,包括我自己的本地副本。我采纳了以下建议:

这就是我在页面中包含jQuery的方式:

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="/Scripts/jquery-3.3.1.min.js"><\/script>');</script>

window.jQuery | | document.write(“”);
同时
document.write()
不可靠,不应使用:

使用document.write()可以将页面内容的显示延迟数十秒 秒数,对于慢速网络上的用户来说尤其成问题 连接。因此,Chrome会阻止document.write()的执行 在很多情况下,这意味着你不能依赖它


是否有其他方法为CDN创建回退功能?

如果您不介意异步加载,可以这样做:

函数回退(){
var-element=document.createElement('script');
element.type='text/javascript';
element.src=https://code.jquery.com/jquery-3.3.1.min.js“;//或指向本地脚本的路径
document.body.appendChild(元素);
}
window.jQuery | | fallback();
setTimeout(函数(){
log(window.jQuery);

}, 1000); // 添加超时,因为脚本是异步加载的
我建议使用3p包,例如或,如果您有多个回退,它们的可伸缩性更高,并且它们可以提供更快的加载性能

fallback.js示例

HTML代码

<html>
<head>
    <!-- **The `data-main` attribute tells the library to load `main.js`** -->
    <script async data-main="main" src="fallback.min.js" type="text/javascript"></script>
</head>

<body>
</body>
</html>
require.js的示例


您可以将动态创建的
元素附加到DOM中。这与
文档具有相同的效果。编写
,但效果更好。但是,顺便说一句,通常不需要为CDN创建回退(可靠性是其要点之一),我不会在我的站点上为CDN创建回退,但是你可以使用@dcangulo的答案,如果你想要的话。你甚至可以在脚本中附加一个
onload
事件,而不是超时。我尝试了这个解决方案,但它不起作用。。。是我面临的问题,也是原因
cfg({
  "libs": {
    "jQuery": {
      "urls": [
        "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min",
        "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min"
      ]
    },  
  }
});

req(function(jQuery) {
  jQuery("body");
});
requirejs.config({
  enforceDefine: true,
  paths: {
    jquery: [
      'https://code.jquery.com/jquery-3.4.1.min.js',
      //If the CDN location fails, load from this location
      'js/jquery-3.4.1.min.js'
    ]
  }
});

require(['jquery'], function ($) {});