【问题标题】:How to create fallback for CDN libraries without using document.write()如何在不使用 document.write() 的情况下为 CDN 库创建回退
【发布时间】:2021-08-05 03:58:26
【问题描述】:

我想包含来自 CDN 的第三方库,例如 jQuery。我还想创建一个回退,所以如果 CDN 失败,我会包含我自己的本地副本。我遵循了here的建议:

这就是我在页面中包含 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>

同时Google is saying thatdocument.write()不可靠,不应该使用:

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

是否有任何替代方法可以为 CDN 创建后备?

【问题讨论】:

  • 您可以将动态创建的&lt;script&gt; 元素附加到DOM。这与document.write 的效果相同,但效果要好一些。但是,AFAIK,通常不需要为 CDN 创建后备(可靠性是其要点之一)
  • 我不会在我的网站上为 CDN 创建后备,但您可以使用@dcangulo 的回答,只要您想要它们。

标签: javascript html cdn fallback


【解决方案1】:

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

function fallback() {
  var element = document.createElement('script');
  element.type = 'text/javascript';
  element.src = 'https://code.jquery.com/jquery-3.3.1.min.js'; // or your path to your local script
  document.body.appendChild(element);
}

window.jQuery || fallback();

setTimeout(function() {
  console.log(window.jQuery);
}, 1000); // Add timeout since script is loaded asynchronously

【讨论】:

  • 您甚至可以将onload 事件附加到脚本而不是超时。
  • 我尝试了这个解决方案,但它不起作用......here是我面临的问题,here是原因
【解决方案2】:

我建议使用像 fallback.jsrequire.js 这样的 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>

主 JS 文件

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");
});

require.js 示例

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 ($) {});

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    相关资源
    最近更新 更多