Fall back to use a jQuery file on your web server, if it can’t be loaded from CDN

26 / Jul / 2016 by Poonam Baveja 0 comments

Content Delivery Network is a system of distributed servers that hosts various resources such as CSS, images, JavaScript files etc. Companies like Google, Microsoft, Yahoo etc. provides a free public CDN to download resources instead of hosting it on your own server.

Advantages of using a CDN:-

1. Distributed CDN servers : The jQuery file can be downloaded from the closest CDN server.

2. Browser Caching : There is no need to download jQuery file from CDN again and again. For eg- If a user has visited a webpage that uses jQuery from a CDN, the jQuery file has already been cached by the browser and if same user arrives at your page, there is no need to download it again.

3. Parallel Downloads : There is some browser limit on how many files can be downloaded concurrently from a given domain. This number varies from one browser to other.If the jQuery file is on a CDN, it is being downloaded from a different domain. So it can be downloaded without any delay.

4. Reduced server load : Since CDN server handles the HTTP request for jQuery file, so the load on your web server is reduced.

Disadvantages of using a CDN:-

Clients may block the Content Delivery Network. So you may have to request your client to unblock the CDN.

What if the required jQuery file cannot be downloaded from CDN?

Let assume that, we are not able to download jQuery from CDN either Content Delivery Network is down or because of some network issue. In this case we will have to fallback to use jQuery file that we hosted on our own server.

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<script> window.jQuery || document.write("[script src='Scripts/jquery-2.1.3.js'][\/script]¬");</script>

If jQuery is successfully downloaded, jQuery property is added to the window object (window.jQuery). If this property is not found then jQuery is not downloaded. So in this case we are writing a script tag to fallback to the local jQuery file as shown above.

FOUND THIS USEFUL? SHARE IT

Leave a comment -