Search code examples
javascriptcsspackagelibrariescdn

How to choose a CDN to load JavaScript & CSS libraries


What kind of reasoning should I do in order to choose a specific Content Delivery Network (CDN) to load JavaScript and CSS libraries into my website development projects?

I see that there are some options (e.g., BootstrapCDN, cdnjs, unpkg, jsDelivr and possibly others), but I don't understand when I should use one over the others.

As an example, examples in Bootstrap documentation show BootstrapCDN and jsDelivr, while aos uses unpkg, and so on.

The first thing that comes into my mind is that there could be differences in how fast they are and how much they are used (so, if I use the one with the largest market share, I will be more likely to have my users already have the libraries in their browser's cache), but I'm not sure it this is just being nitpicky or if these reasonings are legitimate.

Also, once I pick a CDN to load a script, are there valid reasons to always use the same for other scripts as well?


I usually use npm to download scripts into my dev environment and pack them in a single bundle, but there are times when I want to keep one or more of those scripts non bundled (i.e. they are used on a single page and I don't want to load them everywhere); in this situation, using a CDN is probably better than loading them locally, hence my question.


Solution

  • If your use is pretty generic it’s likely that you won’t see a large performance benefit from one CDN to the other when comparing bigger names like cdnjs, jsDelivr, and unpkg. These three all use large CDN providers for the actual distribution of packages and have similar caching strategies.

    Taking in to consideration the fact that some popular CDNs could already be cached by your users’ browser could be worth doing. If your users are focused in a specific market some providers may have an advantage based on their CDN provider - jsDeliver for instance uses Quantil as one of their CDN providers which has points of presence in China that could improve performance for that market.

    These CDNs are very useful in projects that don’t use a JS preprocessor or bundler that can generate bundles from dependencies. Since you’re already building bundles you could also look in to a concept called code-splitting. This concept would split your bundles into smaller chunks and those chunks would only be loaded as-needed as your user navigates around the application. This would keep a common dependency management strategy (using package.json and your package manager) rather than mixing two schemes with requires and <script src=“...s.

    If you’re using a bundler like Webpack or are building a web application using a front end framework this is possible with some minimal configuration and your bundler/framework of choice likely has a guide for implementing it.