Hacker News new | ask | show | jobs
by hnarn 2558 days ago
Please excuse me if this is a dumb question, because my primary job isn't in web development, but what is really the benefit of using javascript code from a CDN rather than hosting it yourself? The way I see it, you're opening yourself up for massive potential trouble by essentially giving someone else a free pass on running whatever code they wish on your website, and you're giving up this privilege for what? I honestly don't understand, but it's so popular that I'm assuming I've missed something.
2 comments

Hosting javascript from a CDN is useful for a few things

a) seperates static hostic (js/css/images) from dynamic hosting, which require different tuning and traditionally may run better on separate machines

b) you used to get some parellism benefit from multiple hostnames, that might be gone with http/2, but then you may not want head of lime blocking interacting between html and css/js

c) a good CDN will get your js/css/images to your users faster than if they got them directly from your origin servers, if your assets are of significant enough size to overcome the overhead of connecting to the CDN, and the chance that the CDN has a cache miss (depends on usage). A good CDN is using geo aware DNS and/or anycast to get clients to a datacenter that's near to them, and chances are your origins are only in one to three locations. For one site I worked on, when we did a redesign that doubled the page weight, but also moved serving everything behind a CDN, the page load time ended up about the same, so the CDN basically let us double our page weight for free (I would have preferred that we just keep the page smaller and get a faster site, but I don't get to make those decisions)

d) some people claim there's a reasonable chance of browser caching if you use a public CDN path, although personally, I expect that's very small -- there are so many public CDNs and so many versions of all the libraries and most browsers have fairly small local caches.

Yup.

The benefits of a CDN:

1) You don't pay for the bandwidth (in some cases)

2) If enough resources on the web request it, the client may have it cached locally already, causing faster load times.

3) If you request a lot of resources, you get more threading because the amount of simultaneous request to the same host is limited for most platforms (applicable when the source is not cached), but using HTTP/2 negates this issue as well.

4) Based on your location, the CDN can serve the content from a datacenter closest to the end-user (not all CDN's have this feature), resulting in faster transfers as well.

The question remains if this is worth it. For some stuff, it is (think Google Fonts for example), for most, you get version fragmentation, which makes the odds of someone having it cached a lot lower. Add all the other things that can go wrong, and using a CDN stops making sense in a lot of cases.