Search code examples
javascripthtmlcdnfallback

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?


Solution

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