简体   繁体   中英

How to create fallback for CDN libraries without using document.write()

I want to include 3rd party libraries, such as jQuery, from CDN. I also want to create a fallback so if the CDN fails, I include my own local copy. I have followed the suggestion here :

This is how I include jQuery in my page:

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

At the same time Google is saying that document.write() is unreliable and should not be used:

Using document.write() can delay the display of page content by tens of seconds and is particularly problematic for users on slow connections. Chrome therefore blocks the execution of document.write() in many cases, meaning you can't rely on it.

Is there any alternative method to create fallback for the CDNs?

If you don't mind loading it asynchronously you can do it like this:

 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

I recommend using 3p packages like fallback.js or require.js given they are more scalable in case you have multiple fallbacks and they give you faster loading performance.

Example of fallback.js

HTML CODE

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

MAIN JS FILE

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

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

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