How to load jQuery locally when CDN fails ?
In this article, we will learn how to load our local jQuery file when CDN fails. First of all, why we should use CDN if there is a chance that it fails. There are many advantages of using CDN rather than local jQuery files.
Some advantages of using CDN are as follows.
- It reduces the load from our server.
- jQuery framework loads faster from these CDN, so it saves our bandwidth.
The chances that the CDN fails are rare. But it doesn’t mean that it will never fail. So we have to take it into consideration.
How to check our CDN script loaded properly or not?
We can check that our CDN script is loaded or not by checking the type of any variable or function that should be present after a script load. If we get the type ‘undefined’, it means our CDN fails.
If we just remove any letter from the CDN, then our CDN will not load and it gives the output:
How to load jQuery locally when CDN fails?
First, let’s see how can we link jQuery from our local machine. First, we will download the jQuery library file from the jQuery website and then we will include it in our HTML code like this.
Code for loading jQuery from the local machine:
Note: Use the full path to your downloaded jQuery file. In my case, both HTML and jQuery file is in the same folder. Now, we will see how to load local jQuery in case our CDN fails.
Write the following lines of code, and it will add jQuery from the machine when CDN fails.
<script>window.jQuery || document.write(‘<script src=”jquery-3.6.0.js”><\/script>’)</script>
We are trying to load the jQuery from CDN. If CDN fails, then the “jQuery” variable will be undefined.
In the second line, We will check if the “jQuery” variable is undefined or not, if it is undefined, means CDN doesn’t load then we will load the jQuery file from our local machine.
We will always get this output, even our CDN fails. As we are handling the case that if our CDN fails, add the jQuery file from our machine.