Hooman Bahreini
Hooman Bahreini

Reputation: 15579

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?

Upvotes: 0

Views: 1581

Answers (2)

Subha
Subha

Reputation: 580

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

Upvotes: 0

dcangulo
dcangulo

Reputation: 2107

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

Upvotes: 2

Related Questions