Using A CDN With A Fall Back

In this blog, you will learn how to use a CDN with fall back.

Introduction

Many programmers load jQuery from a local server. There is nothing wrong with that process but there is another option to load jQuery without using the local server, that is, with the help of CDN (Content Delivery network). But while using this CDN, there will be a certain downfall loading the script if the network is not stable. In this blog, we are going to see how to fall back to load the script from a local server if the CDN fails.

Benefits of CDN

  • Caching the Scripts
  • Allow for parallelism
  • Support for https and https and many more

Click here to learn more about CDN.

jQuery library Google CDN link

  1. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  

There is no protocol in the above link, which means that the link will get loaded for both, HTTP and HTTPS protocols based on our domain.

Let’s get into action.

Providing a CDN fallback

Anytime while using a CDN, we need to provide a fallback.

  1. window.jQuery || document.write("<script src='JS/jquery.min.js'><\/script>");    
The above line of JS code is used to provide a fallback to local server when the CDN fails .
 
Complete Code 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  7.     <script>  
  8.         window.jQuery || document.write("<script src='JS/jquery.min.js'><\/script>");  
  9.     </script>  
  10.     <script>  
  11.         $(document).ready(function () {  
  12.             $("#example").html("Testing CDN.. ");  
  13.         })  
  14.     </script>  
  15. </head>  
  16. <body>  
  17.     <div id="example">  
  18.     </div>  
  19. </body>  
  20. </html>  
Result
 

From the above figure, you can notice that the CDN load fails and the jQuery loads from the local server.

I hope you have learned from this blog. Your valuable feedback, questions, or comments about this blog are always welcome.