27 ms·
Please stop using CDNs for external JavaScript libraries
- withinboredom 6y agoI was surprised to see that the cost of another connection wasn't thrown in as a downside. With http2, that cost goes away if the resource is stored at the same domain as the site.
- politelemon 6y agoThat's a really good point now - previously an advantage of using a CDN was that a browser would request a limited number of concurrent connections per domain, so having the static assets spread across domains sped up that initial page load. As HTTP/2 spreads the cost is indeed reduced.
- davidmurdoch 6y agoLoading common libraries from a CDN will no longer bring any shared cache benefits, at least in most major browsers. Here's Chrome's intent to ship: https://chromestatus.com/feature/5730772021411840 https://chromestatus.com/feature/5730772021411840 Safari already does this, and I think Firefox will, or is already, as well.
- edent 6y agoOh, that's interesting. I guess it makes sense from a security and privacy perspective.
- dndvr 6y agoWill this cause performance issues for sites that use static cookieless domains for js, images etc Google themselves do this with gstatic.net and ytimg.com etc
- babuskov 6y ago> Will this cause performance issues for sites that use static cookieless domains for js, images etc > Google themselves do this with gstatic.net and ytimg.com etc Most probably not. The point of cookieless domains is that you can use a very simple web server to serve content (no need to handle user sessions, files are pre-compresses and cached, etc.) and it lowers incoming bandwidth a lot. If you have a lot of requests (images, css, js) the cookie information adds up quickly. Opening video thumbnails from ytimg.com will still be cached for youtube.com as before. The only thing that will change is for embedded videos on 3rd party websites as those won't be able to use caches ytimg.com thumbails from elsewhere.
- pferde 6y agoCouldn't the same thing be achieved by routing e.g. google.com/static/ to a separate simple webserver, instead of using another domain? Or use a subdomain, e.g. static.google.com. The current way seems like needless DNS spam to me...
- dndvr 6y agoEven if Google used a separate highly optimised webserver for google.com/static/jquery.js, users who are logged in would be sending their auth cookies when requesting the library. Given that generally people have slower upload than download, shaving off a few bytes from requests is worth it. I also recall that browsers [used to (?)] limit concurrent requests per domain which this helps work around
- dheera 6y agoI wonder if an nginx plugin could be made to auto-cache CDN javascript/css files and edit the HTML on the fly to serve them from locally.
- oefrha 6y agoYou’re probably thinking about a caching proxy like squid cache.
- daveFNbuck 6y agoYou can set up a path that does a cached proxy to the CDN and just edit the HTML yourself. It's a bit annoying to get the cache settings to work properly, but editing the HTML is easy.
- ex_amazon_sde 6y agohttps://decentraleyes.org/ https://decentraleyes.org/
- GordonS 6y agoI'm not sure I understand the threat here. Say I visit SiteA which references jQuery from CDNJS, then later visit SiteB which references exactly the same jQuery from CDNJS - what's the problem?
- dathinab 6y agoIt can be used to track users across domains to some degree.
- mmcwilliams 6y agoNot to be dense but wasn't that always the purpose of running a CDN service for common scripts and libraries?
- daveFNbuck 6y agoThe script wouldn't have to be from a CDN to track people using the browser cache. I could infer whether you've visited a site that doesn't use CDNs or trackers by asking you to load something from that site and inferring whether you have that resource cached by the time it took you to load it.
- mmcwilliams 6y agoThis is true, but if you're running a CDN you have access to cross-domain user information just based on the headers, no?
- daveoc64 6y agoThe CDN is not the place you have to worried about. If Site A loads a specific JavaScript file for users with an administrator account, Site B can check to see if the JavaScript file is in your cache, and infer that you must have an administrator account if the file is there. The attack can happen with different types of resources (such as images).
- arendtio 6y agoDoes someone know why they don't split the cookie storage equally by the top origin? I mean, wouldn't that take care of a whole class of attack vectors and make cross-origin requests possible without having to worry about CSRF?
- fastest963 6y agoThis is being worked on https://github.com/privacycg/storage-partitioning https://github.com/privacycg/storage-partitioning.
- tgsovlerkhgsel 6y agoOne of the problems is that it breaks use cases like logging into stackoverflow.com and then visiting serverfault.com, or (if you do it by top-level origin) even en.wikipedia.org and then visiting de.wikipedia.org. [1] While privacy sensitive users may consider this a feature in case of e.g. google.com and youtube.com, the average user is more likely to consider it an annoyance, and worse, it is likely to break some obscure portal somewhere that is never going to be updated, so if one browser does it and another doesn't, the solution will be a hastily hacked note "this doesn't work in X, use Y instead" added to the portal. And no browser vendor wants to be X. [1] The workaround of using the public suffix list for such purposes is being discouraged by the public suffix list maintainers themselves IIRC, so the "right" thing to do would be breaking Wikipedia. Edit: If done naively on an origin basis right now, it would break the Internet. You couldn't use _any_ site/app that has login/account management on a separate host name. You couldn't log into your Google account with such a browser anymore (because accounts.google.com != mail.google.com). Countless web sites that require logins would fail, both company-internal portals and public sites.
- singron 6y agoIt's possible to get around this with a redirect staple. E.g. if Google wants you to be logged in on youtube.com and google.com simultaneously: 1) User logs in at google.com/login and sets google.com cookies. 2) Server generates a nonce and redirects to youtube.com/login?auth=$NONCE 3) youtube.com checks the $NONCE and sets youtube.com cookies 4) youtube.com redirects back to google.com. Firefox's container tabs can maintain isolation despite this since even this redirect will stay within a container. However there is a usability penalty since the user has to open links for sites in the right container (and automatically opening certain sites in certain containers will enable cross-container stapling again).
- jakub_g 6y agoFor info, this shipped in Chrome 86 just last week: https://developers.google.com/web/updates/2020/10/http-cache-partitioning https://developers.google.com/web/updates/2020/10/http-cache...
- rebelde 6y agoWouldn't a better, but partial, solution be for browsers to preload the top x common libraries? All other libraries would probably have to follow this new rule.
- codegladiator 6y agoPlease no, don't create such barriers.
- admax88q 6y agoEvery other language runtime has a standard library, it's always been a shortcoming of the web IMO
- ValueNull 6y agoIsn’t this essentially what Decentraleyes does? https://decentraleyes.org/ https://decentraleyes.org/
- Forbo 6y agoI've been using LocalCDN, it seems to be more acatively maintained and has a better selection of libraries. https://www.localcdn.org/ https://www.localcdn.org/
- lkschubert8 6y agoAt that point wouldn't it make more sense to just have the browsers include that functionality?
- Polylactic_acid 6y agoAs soon as you add something to JS you have to support it forever. Its better to let sites pick what they need and scrap what they no longer need. JS has already added most of the useful stuff from jQuery. If browsers included a built in version of React it would pretty much lock in the design as it is now without room to remove and replace bad ideas.
- thorum 6y agoOn the other hand, the URL for a common library hosted on cdnjs (or one of the other big JavaScript CDNs) and included on many different websites is much more likely to already be cached on edge servers close to your users than if you host the file yourself.
- arghwhat 6y agoThe time to connect to the CDN hostname will negate any benefit, especially if push can be used.
- Matthias247 6y agoYou can mitigate this by getting your website itself on a CDN. If this is cached, then it's assets (incl javascript), would be too. And by going that route you make sure that all pieces of your website have the same availability guarantees, the same performance profile, and the same security guarantees that the content was not manipulated by a 3rd party.
- GeneralTspoon 6y ago> And by going that route you make sure that all pieces of your website have the same availability guarantees, the same performance profile, and the same security guarantees that the content was not manipulated by a 3rd party. You can already guarantee the security of the file by using the integrity attribute on the <script> tag. And the performance of your CDN is probably worse than the Google CDN (not to mention that you lose out on the shared cache).
- Matthias247 6y agoI agree on the security side if you use that attribute. However: > And the performance of your CDN is probably worse than the Google CDN What means probably? Other CDNs (Akamai, CloudFront, Cloudflare, etc) are also fast. And by pushing one piece of your website on a different CDN you force your users browser to create an additional HTTPS connection which takes additional round-trips, instead of being able to leverage one connection for all assets. This alone might as well outweigh the performance differences between CDNs. Also the "shared cache" benefit might go away, if I read the other answers in this topic correctly.
- deepstack 6y agoGood! The whole idea for doing js on CDN is suppose to make it easier for entry level front dev to be able to start coding. I think that is great for a school exercise, should never be used in business or production sites. And on a side note, very unhappy about how the entry to be a developer has lower significantly over the last 10 years or so.
- lolc 6y agoWeirdly, the piece fails to mention my number on reason for loading libraries from a CDN: economy. Least setup cost and externalized hosting costs mean that unless I have good reasons otherwise, I have to use them from an economic perspective!
- minitech 6y agoWhere is your webpage hosted that makes it not require setup or hosting costs compared to scripts served from the same place?
- lolc 6y agoYou probably want to tell me that adding a few megabytes extra is not going to cost more from the hoster. In most instances this is true. What you forget is that everything has to be configured and maintained. Just ensuring the lib gets deployed to the right place, in the right version, and with the right caching-headers, has cost me hours of my life in some instances. When I let a CDN do it, it was minutes. Those days are over. I don't load static libs any more, so the question doesn't even come up. Except maybe for fonts.
- jabart 6y agoCDNs are misunderstood these days. Caching at the browser across sites is not that important, it caching at a point of presence (POP). This POP being so much closer to your end users brings performance gains because TCP is terrible over distances. QUIC may fix this by it's shift to UDP. I haven't seen a benchmark yet. Security is a concern, use SRI. Reliability can be mitigated with fail over logic to a backup. The part missed is bandwidth. Using a CDN means your web server doesn't have to serve out static files that you are paying per a GB to serve. Small sites it's not much but it does add up. It's a Content Delivery Network not a Cache Delivery Network.
- EE84M3i 6y agoWait, what is the misunderstanding? Aren't these the well known benefits of CDNs?
- deleted 6y ago[deleted]
- dathinab 6y agoCDNs are just a service to handle delivery of static content for you. Their main points (unordered) are: - reliability - delivery speed through closeness to user (having nodes all around the world) - cost - ease of use - handling of high loads for you / making static content less affectedly by accidental or intentional DoS situations That multiple domains might use the same url and might share the cache was always just a lucky bonus. Given that the other side needs to use the exact same version of the exact same library with the exact same build options accessed through the exact same url to profit from cach sharing it never was reliable at all. I mean how fast does the JS landscape change? Given how cross domain caching can be used to track users across domains safari and Firefox disabled it a while ago as far as I know, and chrome will do so soone.
- m463 6y agogo to a webpage that uses a cdn and do view source. it all looks like https://cdn.example.com/foo/bar.js?v=129a1d14ad3 https://cdn.example.com/foo/bar.js?v=129a1d14ad3
- ffpip 6y agoExtensions that act like a local CDN. Page loads faster, more privacy, etc. https://decentraleyes.org/ https://decentraleyes.org/ https://www.localcdn.org/ https://www.localcdn.org/ (fork of decentraleyes, with many more resources)
- sippingjippers 6y agoInteresting, I was already using DecentralEyes. Do you know why the fork happened? What policy does DecentralEyes keep that LocalCDN extends or violates? edit: will be sticking with the original, looks like the fork maintainer made no effort to work upstream first, which is a very bad look for what is essentially a piece of security software. https://gitlab.com/nobody42/localcdn/-/issues/5 https://gitlab.com/nobody42/localcdn/-/issues/5
- ffpip 6y agolocalCDN has more resources than Decentraleyes. It also has very important resources like Google Fonts, some cloudflare resources etc, none of which were present in Decentraleyes (the last time I checked) > will be sticking with the original It's your choice. The fork is better. The maintainer seems a bit more active (more updates) and extremely pro-privacy (I concluded this from his home page and extension settings)
- mimimi31 6y agoI was thinking about switching from decentraleyes too, but I'm hesitant to install a "can access all sites" extension that hasn't been vetted ("recommended") by Mozilla.
- ffpip 6y agoLocalCDN is the most offline extension I have seen. It even opens donation pages locally, instead of opening the author's website. He says ''I think it is better if your public IP address is rarely listed in any server log files.''
- 6y ago
- MattSteelblade 6y agoAs a user, I recommend using Decentraleyes for Firefox[1] and Chrome[2]. [1] https://addons.mozilla.org/en-US/firefox/addon/decentraleyes/ https://addons.mozilla.org/en-US/firefox/addon/decentraleyes... [2] https://chrome.google.com/webstore/detail/decentraleyes/ldpochfccmkkmhdbclfhpagapcfdljkj?hl=en-US https://chrome.google.com/webstore/detail/decentraleyes/ldpo...
- deleted 6y ago[deleted]
- paulgb 6y agoThere are some good reasons in here (especially privacy), but I'm not convinced by the security point. It seems like the example linked about British Airways was JS under the britishairways.com domain being changed, not a third party CDN. Incidentally, a few years ago when people were loading third party scripts over HTTP, I demoed a fun hack where, if you control a user's DNS, you could redirect queries to popular CDNs to a proxy that injects keylogger code and tells the browser to cache it indefinitely. Because at the time almost every site included either jQuery or Google Analytics, you'd have a persistent keylogger even after the user switched to a more secure connection. How far we've come!
- Felk 6y agoIs that demo of yours available somewhere? It sounds interesting and I'd love to read up on it
- paulgb 6y agoI was able to find a video of it: https://www.youtube.com/watch?v=_BUg9NzdLd4 https://www.youtube.com/watch?v=_BUg9NzdLd4 I think this is the code: https://github.com/paulgb/cachebeacon https://github.com/paulgb/cachebeacon It basically just runs two servers: - A DNS server that resolved a list of domains to its own IP. - An HTTP server that looked at the HTTP host and proxied requests to the upstream server. If the content type or extension indicated that the response was JavaScript, it would add the payload and set cache headers to cache as long as possible. - A special HTTP endpoint on the proxy server to capture data sent back from the payload.
- maple3142 6y agoJust wondering. Can "integrity" be used instead of url to provide better caching? Because it is based on hash, which should be more reliable than just url.
- RL_Quine 6y agoThat would be a super-cookie though.
- lucb1e 6y agoHow would specifying what content the library should have (to preserve integrity) lead to tracking?
- im3w1l 6y agoCaching across sites at all means you can see if it loads quickly or slowly to make inferences. Non-obvious tradeoff imo.
- XCSme 6y agoIt's not about how fast it loads, it about whether it actually requests the file from the server or not. See my comment above, if you have "x.js" in your cache and it's your first time on this site, it means that you previously visited another site that contains "x.js".
- im3w1l 6y agoIn cache - high speed, fetch from server - low speed. Isn't that how you detect it?
- XCSme 6y agoThe problem is not that you can detect it on the client,but you can also see it on the server. On the server you see that user requested the HTML for the page and other resources, but never requested X.js. You could keep a count of requests, per user per file.
- jaimex2 6y agonpm, bower etc more or less killed this pattern I thought?
- user_501238901 6y agoYou'd be surprised how many new websites out there are still made by importing JS from a random CDN, no version control of course, code is uploaded manually through FTP
- jopsen 6y agoI think we should be amazed at how far amateurs can go :) In a world where all websites have to be perfect, we would have far fewer websites.
- mistrial9 6y agoWhat does Wordpress do ?
- XCSme 6y agoI think this is like asking "What would Jesus do?", but with a worse role-model. The problem with WordPress is a lot bigger with the Themes/Plugins than with the platform itself.
- a_humean 6y agoDuring code review we just discovered that a somewhat popular npm library used a CDN for its assets (images of flags corresponding to country iso codes), forcing us to reimplement without the library.
- quickthrower2 6y agoWe need another new competing module system to screw up all the CDNS!
- martini333 6y agoA DNS lookup will also affect speed
- kijin 6y agoNot to mention another TCP handshake, TLS handshake, certificate validity checks, etc. HTTP/2 changed everything. Now the fastest way to serve your assets is to push them down the pipe that has already been set up.
- ThePhysicist 6y ago> Latest software versions automatically when the CDN updates. I'd also be very careful including a JS library from a CDN that gets auto-updated to the latest version, this might break your site without you noticing. We did this with our own JS library (Klaro - https://github.com/kiprotect/klaro https://github.com/kiprotect/klaro), for which we offered a CDN version hosted at https://cdn.kiprotect/klaro/latest/klaro.js https://cdn.kiprotect/klaro/latest/klaro.js. We stopped doing that with version 0.7 as we realized we could not introduce any breaking changes without risking to break the websites of all users that were using the "latest" version. So what we do know is that we only automatically update minor releases, i.e. we have a "0.7" tag in the CDN that will receive patch releases (0.7.1, 0.7.2 , ...) and which users can safely embed in their websites. That said we always recommend users to self-host their scripts as well and to use integrity tags whenever possible, it's usually better from a security and privacy perspective as well. Like most JS libraries Klaro is quite small (45 kB compressed), so the loading time is dominated by the connection roundtrip time, which again is dominated by the TLS handshake time. For our main servers in Germany we have a roundtrip ping of around 20 ms (for most connections from Germany), and with the TLS negotiation it takes about 60-100 ms to serve the script file from our server. If the server connection is already open that time reduces to 20-40 ms. So the benefit of hosting small scripts with your main website content is that your browser doesn't have to do another TLS handshake with the CDN, which for small scripts can dominate the transfer time. If you then use modern HTTP & TLS versions you can reduce the transfer time quite a bit.
- laurent92 6y agoThe CDN can’t swap the files under us, if we activate the CSP, content security policies, which are activated once per domain. They require to provide <script> tags with the “integrity=“ attribute holding the hash of the file.
- ThePhysicist 6y agoThat will still break your site if the CDN updates the file because it won't load anymore. The point the author made was that people use libraries distributed by CDNs to get auto-updates and fixes, sadly that won't work in combination with CSP as you'll still have to update the integrity tag manually. We deliver integrity tags for our CDN files as well btw (https://github.com/kiprotect/klaro/blob/master/releases.yml https://github.com/kiprotect/klaro/blob/master/releases.yml), that doesn't solve the auto-updating problem though.
- pkz 6y agoFun case from Sweden: the central government website for healthcare included js from a third party with no integrity hash. Third party got hacked and they changed the js to mine cryptocurrency over the weekend. Thousands of people participated in mining...
- edent 6y agoOoh! Do you have a source on that? I couldn't find anything in English language media.
- aliswe 6y agoMaybe this, the website was the swedish police https://www.privateinternetaccess.com/blog/swedish-police-website-hacked-to-mine-cryptocurrency/ https://www.privateinternetaccess.com/blog/swedish-police-we...
- quickthrower2 6y agoThis is where browsers need to be locked down a bit more. The web api, and available local compute resources should be governed by permissions. Yeah it'll break a few sites at first!
- Polylactic_acid 6y agoIt would be sufficient to just put a red triangle on the tab pointing out this one tab is using high cpu.
- duxup 6y ago>But if you are truly worried about speed, surely your whole site should be behind a CDN – not just a few JS libraries? Does it have to be all one or the other? I feel like this kinda hand waves away an advantage.
- ignoramous 6y ago> British Airways' payments page was hacked by compromised 3rd party Javascript. A malicious user changed the code on site which wasn't in BA's control – then BA served it up to its customers. That's the only reason you should ever need to not load any 3p javascript including google-analytics. If you're like me and want to avoid loading popular javascript libraries from CDNs but want those webpages to work, get the Decentraleyes plugin: https://en.wikipedia.org/wiki/Decentraleyes https://en.wikipedia.org/wiki/Decentraleyes
- Spivak 6y agoOr at least do subresource integrity so you know you’re getting the exact same file every time.
- rgbrenner 6y agoThat can mitigate the damage, but any user with a browser that doesn’t support it will still be compromised. If it’s an important part of the site, it might make the failure more obvious in newer browsers.. but small libraries used on only some pages might not be noticed quickly... so you’d probably also want to test all of your resources regularly.. and even then the time between those test runs may allow some users to be compromised. So using it is a good idea but it’s not a fix for the actual problem.
- maple3142 6y agohttps://caniuse.com/subresource-integrity https://caniuse.com/subresource-integrity It is basic available for every browser except IE and Opera Mini, so I think it is user's problem to use an old browser that don't support a wide supported security feature.
- emn13 6y agoMight as well simply block IE users outright at this point; it's just not worth the risk (and classic edge is close). It's probably better user experience to be upfront about issues than pretend you actually test and support all those old versions (unless you do... but why?)
- anticristi 6y agoShould you also stop serving "analytics.js" from Google's website and serve it from your own website?
- Doctor_Fegg 6y agoYes. (Matomo is your friend.)
- anticristi 6y agoThis is fking awesome. Thanks! I put switching to Matomo on my TODO.
- XCSme 6y agoIf you like Matomo you might also want to have a look over https://usertrack.net https://usertrack.net, but depending on the features you are interested in, the free version of Matomo might be better for you.
- NikolaeVarius 6y agoJust block JS entirely. 99.99% of sites are worthless anyway, its not hard to enable JS on sites you want to use
- sp332 6y agoI want to discuss a (minor) antipattern that I think is (slightly) harmful. It's caching, not cacheing.
- lazyjeff 6y agoSome of the time, web developers are using CDNs because they want to save 5 minutes from downloading and hosting it on their own servers, or they want to not have to add it to their package.json. I've noticed this with novice web developers, where they just want to get something working up as fast as possible. This practice of linking to a CDN or external URL for a js library used to be heavily discouraged, called "hotlinking", but it seems like many javascript libraries now are fine with it (even encouraging it). I see a similar problem with Google Analytics or Google Fonts, where you're sacrificing user privacy and agency in exchange for developer convenience. In a slightly more privacy-centric era (perhaps in a few years), I think people will consider this practice unethical, as the web developer is sending their visitors off to fetch and run javascript code from a third party's computer. The security, usability, and privacy problems noted by the article are not worth the few minutes saved by the developer.
- 734129837261 6y agoLet us say that you work for or own a website with 1m unique visitors per month. Let us assume your average JS library size that can be cached and outsourced totals 400 kilobytes (that's on the low end). 1 million * 400 kilobytes = 400 gigabytes For AWS the entry level tier per gigabyte is $0.15/GB. That is a whopping $60 USD per MONTH that you can save by running your scripts on a CDN. So, yeah.
- sergeykish 6y agoAnd someone is paying that...
- eeZah7Ux 6y agoThe users are paying for it with their privacy. CDN providers are not charities: they sell traffic metadata.
- sergeykish 6y agothat's what I meant, million data points costs $60
- heartbeats 6y agoWhy are you serving 400kb of JavaScript? Why are you paying $0.15/GB? These numbers are certainly not on the low end.
- quickthrower2 6y agoI assume that it's "for the sake of argument" https://www.ldoceonline.com/dictionary/for-the-sake-of-argument https://www.ldoceonline.com/dictionary/for-the-sake-of-argum... Also it's a bit like a proof. By assuming worse numbers, and arriving at $60, your better numbers will only prove the point even more.
- heartbeats 6y ago
- xthestreams 6y agoMostly opinions without data, as usual. Why can't we as a community switch to a more serious scientific/engineeristic approach, at least in those areas where it is easy to do so? Why should I trust this blog post on the "Caching" point, for example? It's got no data and no references. "What are the chances that your user has visited a site which uses the exact same CDN as your site?" ... hey, you can measure that.
- whyagaindavid 6y agoThis depends on the CDN. Lets say you are using google or cloudflare CDN. They have more engineers and better security processes – and work 24X7 -365 days – continuous monitoring – than you remembering to download jquery update. What about if you are on holiday (post/pre COVID era)? BA is not the best example… Rename your article to: Please stop using ‘unknown CDNs’…
- sergeykish 6y agoPage contains 3rd party script without subresource integrity <script type='text/javascript' src='https://stats.wp.com/e-202041.js https://stats.wp.com/e-202041.js' async='async' defer='defer'></script>
- basilgohar 6y agoAm I the only one that feels using CDNs comes with very little benefit compared to just hosting all resources locally? Almost all security issues go away with locally hosted (i.e., same domain or another domain controlled by the website), plus you avoid an extra DNS lookup, and you still get caching on the same site. I realize there are benefits, but are the benefits so extreme that they merit all the hype around CDNs? So many developers talk about them like the web would crawl to a halt if they were stopped, but I think that they have their own slippery-slope of problems that has resulted in folks just hand-waving away the expense of web assets since it's a hidden problem from the developer. I doubt actual bytes transferred and latency are affected in a significant way as folk that promote CDNs claim. It'd be nice to see actual comparisons in a real world scenario. Keep in mind, web site responsiveness is not just linked to download time/size, but also asset processing. If your page is blocking because the JS is still being parsed, the time you saved downloading it is moot.
- old-gregg 6y agoYes, the benefits are substantial. I used to have a static web site served out of a Dallas data center, with a great network connection, from a powerful bare metal machine that did nothing else. Sitting in Austin, it felt instant, equal to localhost speed, until I tried accessing it while traveling, especially overseas. It's not just geographic latency you're addressing with a CDN, you're also reducing the number of network hops. It's not uncommon to experience higher latency going from SF to San Jose datacenter just because you're on a "wrong" ISP. A good CDN usually has a POP on the same network as you.
- esperent 6y agoI live in Vietnam and frequently give tech advice to people regarding websites they are developing. Most sites on the works fine, but I can tell straight away when someone has hosted their site like you have described - because it will take >5 minutes to load! And they'll be telling me that it's fine, and I have to explain, yes, it's fine if you only want people in the same country as you to access the site. If you want it to work worldwide, you'll have to do better. Fortunately, these days that just means creating a free Cloudflare account.
- pdevr 6y agoI believe a site should load all JavaScript files from its own domain if it can. There are problems, but they have solutions too. As an example: Problem: You can use a home-grown tracking solution, but, if the site has to be sold, how do you provide independent third party verification of your traffic details? Having Google Analytics helps you to do that. Solution: Install and configure AWStats or Webalizer. Many lower tier hosts have these built into their offerings. Provide those statistics to interested buyers.
- alkonaut 6y agoCan’t js build tools pack together my code with the third party libraries and then also tree-shake out all the bits I’m not using?
- alibarber 6y agoI started my career, and have spent most of it, working in places where the production network was (almost) airgapped from the entire internet (MPAA accredited facilities). I would say that the general quality of software and and robustness when it comes to dependencies is so much greater in these places. If you want to use some library, it’s up to you to get it, and its dependencies, check the versions are compatible and package it up and build it all internally. Yup, it’s work... Do you need this library? Is it actually any good? Is the license compatible with our usage? This is all basic code quality stuff that’s often completely overlooked when people can just pull in whatever junk from whatever trendy repo is the hotness nowadays. And then when that goes down/bankrupt - it’s up to you to fix something you’ve no control over.
- jrsj 6y agoThis is probably better from a quality perspective and also probably not worth the time it would take in 90% of projects. That being said I'm amazed how much production software depends on multiple libraries that are developed and maintained by a single person as a hobby.
- madeofpalk 6y agoYeah like as a frontend/web developer, most of what we do is make what are essentially Wordpress themes for some company that really doesn’t matter or do much important.
- ClikeX 6y agoThat one person (sometimes) puts in more effort into that single library then I've seen some agencies put into a client project.
- wwweston 6y agoIntrinsic vs extrinsic motivation. It's pretty common for someone building a library to do so for the utility, scratching a real itch. Not universal (people build libraries to be someone who built a library, too), but common. It's very common for agencies to be building client projects in order to bill for it. Sometimes there's a special alignment where the client is also primarily interested in spending an allotted budget so long as there's a plausibly adequate deliverable.
- anm89 6y ago> So what? This isn’t the biggest issue on the web. And I’m certainly guilty of misusing CDNs like this. I just love this person's attitude. So many blog posts try to beat you over the head with some opinion that doesn't feel like such a big deal. The disclaimer on this actually gave the author a lot of credibility in my mind. Great post, and I will consider my opinion changed on this topic.
- deleted 6y ago[deleted]
- jedberg 6y agoThe best point in this article is that your site should already be on a fast CDN. Focus on that and then none of the other advantages of JS on a CDN matter (and you don't have to worry about the downsides).
- uniqueid 6y agoStop using externally-hosted fonts, too! It's 2020. I don't visit websites to marvel at their beauty; I just want to read the article. So I'm not going to compromise my privacy just to read seven or eight paragraphs of text in Myriad instead of Helvetica.
- smt88 6y ago> So I'm not going to compromise my privacy just to read seven or eight paragraphs of text in Myriad instead of Helvetica. uBlock Origin allows specifically blocking external fonts. > I don't visit websites to marvel at their beauty Using the right font is rarely about beauty. Yes, it's often aesthetically pleasing. But good fonts can have lots of practical effects for people, especially those who are disabled or aging. It's fine for you not to care about fonts and to block them, and it's fine for people to host fonts themselves (if the license allows), but it's misinformed to complain that all non-standard fonts are a meaningless aesthetic contrivance.
- uniqueid 6y agoThe alternative to "link to custom fonts on a third-party server" isn't "don't use custom fonts" though, it's "host them on your own server". In any event, the point about accessibility is wrong because it's more common for designers to use custom fonts that are harder to read than easier.
- anaganisk 6y agoYou're not everyone's typical customer. Stop generalising personal preferences
- rini17 6y agoHe is not generalising, you are. Why is that some personal preferences are met with such hostility here (unless carefully wrapped with disclaimers that it's meant only personal)? I am running my own recursive DNS resolver and some sites pull crap from such a sheer variety of sources that before it all gets cached, the load times remind me of dialup 20 years ago.
- vaccinator 6y agoStop using Google for fonts while you're at it...
- A7med 6y agono
- seanwilson 6y agoThe pattern I don't like is the one where people load JS like jQuery from a CDN with a local fallback if that doesn't work: - realistically, nobody is going to be testing if the fallback functionality works as the site grows so you're going to get weird breakages if the fallback misbehaves (e.g. your local file is a different version). - big CDNs go down so rarely it's not worth thinking about (and if it is serve it from your own site) - it's easy nowadays to put your whole site behind a CDN so there's little point (the article debunks the caching advantages) I think people are just copy/pasting snippets that do this from somewhere without thinking.
- arielm 6y agoWithout real examples this just gives more reasons to load big libraries, such as jquery, from popular CDNs. Let’s take jquery for example; Speed - if everyone loaded jquery from the official CDN, considering the usage of jquery is high, you’re very likely to get a speed improvement. Faster website = happier customer (and happier search engine, which could mean more customers) That to me is enough. But... I do agree that if everyone uses that CDN and it gets compromised everyone is in trouble. That to me is enough reason not to use it. The article doesn’t do this one any justice IMO + it’s a personal decision because major CDNs don’t get compromised every day, so convenience might win here.
- sneak 6y agoAdditionally: Please stop using Javascript as an essential component in the rendering of non-interactive pages. It’s trendy these days to require client JS for every old webpage, even ones that work just like webpages did in the pre-JS-all-the-things days. This breaks graceful degradation, uses more power and bandwidth, takes longer to load, and is a security risk, for little or no benefit. Please stop doing it.
- softwaredoug 6y agoI recall being regularly surprised how infrequently CDNd JavaScript libraries were cached locally. In my testing, even something popular like jQuery or Bootstrap has enough different versions and CDN hosts that it wouldn’t be cached ~50% of the time. Perhaps what’s really needed is some kind of browser based package versioning and management system? Where your CDNs jQuery 1.10 is seen as a mirror of mine, with perhaps even some signing and authority of libraries not directly hosted on the host server? (I’m probably talking about something that already exists or has been discussed I’m sure...)
- tracker1 6y agoI understand the sentiment, and disagree on a few points... if you're doing more adhoc enhancements using jquery, lodash or some chart/graph library... there's a decent chance that there's caching/reuse in play. If you're building a specific application, then I'm less likely to rely on a CDN... I think applications should largely deliver all of their own resources. If you're in financial or security (military) applications, there may be legal, resource and other requirements that supercede what you can do. It's not a one size fits all... that said, modern web application development centers around resources via npm, and largely delivered in your appliation bundle, so it's less of a concern in the common case these days imho.
- kizer 6y ago$$$
- ocdtrekkie 6y agoWhen packaging apps for Sandstorm, eradicating these sorts of external dependencies is one of my top irritations. Not only do projects themselves rely on them, but components they drag in also bring in their own CDN dependencies. FontAwesome is the top offender today, call out to a third party server just to avoid hosting your own toolbar icons. Recently, Sandstorm added the ability to block apps from loading external client-side scripts, and I hope more app platforms and hosting platforms adopt similar so that doing it goes out of style.
- thomasfromcdnjs 6y agoAfter starting cdnjs nearly 10 years ago, I still use it just for convenience sake if I am building some rough site. I use webpack etc for big projects.
- szundi 6y agoFree CDN does not cost anything compared to other solutions owned/payed be me.
- Dyaz17 6y agoRegarding the security aspect, I created GuardScript to help catch malicious 3rd party (or 1st party) javascript changes: https://www.guardscript.com/ https://www.guardscript.com/ . You should use if you own a SaaS service that require your clients to include your Javascript library in their page, and when you can't use Subresource Integrity.
- PaulHoule 6y agoThis browser extension undoes this phenomenon as much as it can: https://decentraleyes.org/ https://decentraleyes.org/
- GeneralTspoon 6y agoAlmost every point in this post is incorrect and/or exaggerated (except for the Privacy one): > Cacheing. I get the superficial appeal of this. But there are dozens of popular Javascript CDNs available. What are the chances that your user has visited a site which uses the exact same CDN as your site? Quite high - if you're using the Google CDN I'd imagine. > Speed. You probably shouldn’t be using multi-megabyte libraries. Have some respect for your users’ download limits. But if you are truly worried about speed, surely your whole site should be behind a CDN – not just a few JS libraries? (a) Some websites/web apps do actually need to load a lot of JS to function properly (e.g. Google Maps). (b) Putting the HTML of a website into a CDN introduces extra complexity around making the html stateless (cookies, user data, etc.) + the issues that come from having to cache bust the CDN every time some dynamic content on the page is updated > Versioning. There are some CDN’s which let you include the latest version of a library. But then you have to deal with breaking changes with little warning. So most people only include a specific version of the JS they want. And, of course, if you’re using v1.2 and another site is using v1.2.1 the browser can’t take advantage of cacheing. Yeah, don't use library/latest.js. But then this basically boils down to the same argument as point 1 ("Caching"). > Reliability. Is your CDN reliable? You hope so! But if a user’s network blocks a CDN or interrupts the download, you’re now serving your site without Javascript. That isn’t necessarily a bad thing – you do progressive enhancement, right? But it isn’t ideal. Fair enough - depends on your CDN. The Google CDN is probably more reliable than whichever one you're going to pay for instead (not every site can/should be put on Cloudflare for free-ish). > Privacy Yup - this is the real valid issue IMO > Security. British Airways’ payments page was hacked by compromised 3rd party Javascript. A malicious user changed the code on site which wasn’t in BA’s control – then BA served it up to its customers. If OP had actually read his own link, they would have seen that the British Airways JS in question was loaded _from their own CMS_ - not an external CDN. Ironically, in this case - it probably would have been harder to hack the CDN. Plus, always use SRI.
- youngtaff 6y ago>> Cacheing. I get the superficial appeal of this. But there are dozens of popular Javascript CDNs available. What are the chances that your user has visited a site which uses the exact same CDN as your site? > Quite high - if you're using the Google CDN I'd imagine. Quite low in reality as there's no critical mass – most sites don't use the same versions of common resources. Google fonts is one of the better candidates for shared caching working but resources just don't live in the browser cache for very long (Facebook, Yahoo studies)
- quickthrower2 6y agoWhat if you are using hotjar, google analytics etc. Maybe those companies should provide the scripts for you to serve up from your site.
- MrStonedOne 6y ago> But if you are truly worried about speed, surely your whole site should be behind a CDN – not just a few JS libraries? There is an argument for being more efficient with cdn redirects. The ideal cdn'ified site ensures that all requests that are always served from origin goes directly to origin, and all requests that are cachable go through a cdn, this means seperate domains or subdomains.
- qudat 6y agoI'd like to go on a slight tangent: > You probably shouldn’t be using multi-megabyte libraries. Have some respect for your users’ download limits. Can you imagine what would happen if BE languages had to deal with this problem? Want to pull in 30MB `numpy`? Too bad, find something smaller. Understanding this problem illuminates why there are so many one-liner npm modules instead of monolithic utility libraries. Other than embedded developers, who else has to deal with code size?
- megous 6y agoAnother point to consider is that CDN may be blocked or very unreliable in some country. So you may be excluding people from, say, China. If you use google cdn for JS, or fonts (less problematic).
- waffletower 6y agoIf you care about the uptime and deployability of services, use artifact managers and cache dependencies. Pin top-level dependencies. In the Javascript ecosystem, I imagine you will need to fork and pin some transitive dependencies where necessary. ¯\_(ツ)_/¯ The answer to Jimi Hendrix's proverbial question, "Are you experienced?" by library maintainers in these cases is usually: "No".
- docuru 6y agoReliability and Security concern mentioned in the posts could also happen with or without using CDN. Another issue with modern web apps is, they update almost every day. Imagine bundle and reload the whole js file with only small changes is not a great idea
- CGamesPlay 6y agoI'm super happy that this is becoming the new standard, but for a different reason. I hate it when my local development environment has to call out to the internet. I want to be able to do my work from a spotty wifi connection, or on an airplane! For this reason, none of my projects have ever used these external CDNs, and now browsers are making it so this isn't even a detriment to my users. Great! [append] By the way, the article title is not what the article intends it to be. He wants to say "please stop using shared CDNs for external JavaScript dependencies". There's nothing wrong with CDNs.
- fyfy18 6y agoWhile we are on the topic of CDNs I'd like to remind everyone: S3 is not a CDN, and you should not be serving assets from it directly S3 is convenient, but assets are only served from a single region, and sometimes traffic from other geographic regions can be very slow. I'm in Europe and personally have seen excruciatingly slow transfers from us-* S3 buckets (10s of kbps, over my 1gbit connection). Even if you only expect files to be requested without being edge-cached, just sticking Cloudfront on top can delivery files much faster.
- avighnay 6y agoA key reason for this, if I may guess is that most libraries today provide tutorial/get-started code which uses CDN. I assume most just copy paste these code snippets into their projects. My go to test for my QA team is to have them add a zero internet test case. Test your product in localhost with the network switched off.
- coldtea 6y ago>I get the superficial appeal of this. But there are dozens of popular Javascript CDNs available. What are the chances that your user has visited a site which uses the exact same CDN as your site? For the 2-3 most popular, almost 100%?
- TomGullen 6y agoCould browsers that cache resources cross reference the integrity check and load their cached version even if the domain is different as a speed optimisation?
- mcovey 6y agoI think they could, and it would be a good idea too. Browsers could also possibly ignore server-sent cache directives for scripts with SRI hashes, or at least consider them immutable by default, since there is virtually no possibility of any script with the same hash referring to a different file.
- CodesInChaos 6y agoThat opens up fingerprinting attacks browsers want to avoid. They're actually moving in the opposite direction, and consider disabling caching across top level origins.
- flohofwoe 6y agoI don't get the point the first point about caching. Only the very first user of a specific website in a specific region sees a slow download from the origin server, every other user of that website in the same region gets the cached files from the CDN node. No matter how and when a file got onto a CDN node first, the vast majority of users will benefit from caching (it doesn't matter whether it's a "popular" JS library, or any other file that's only used by your website).
- timvisee 6y agoI agree, please host it yourself. If your server is somewhat fast, supports HTTP2 and whatnot, clients will be able to pull these assets in crazy fast. If you're hosting a ginormous website a CDN might become interesting to improve worldwide latency. I even saw people arguing using a CDN 'saves' a DNS request as the CDN is probably already cached. This is of course utter bullshit as this request is already made when doing the page request.
- davidkhess 6y agoRecounting my own experience w/ unpkg: They had an issue where they were responding with 302s redirecting to malicious adware: https://twitter.com/unpkg/status/852660203275276289 https://twitter.com/unpkg/status/852660203275276289 They promised a post-mortem which (to my knowledge) never happened: https://twitter.com/unpkg/status/852666784792444928 https://twitter.com/unpkg/status/852666784792444928 I removed unpkg from my infrastructure and won't be using any of these services again. The minimal gains aren't worth the risk in my estimation.
- thomashabets2 6y agoReminds me of my (very limited) experience in China: https://blog.habets.se/2017/10/Internet-in-China.html https://blog.habets.se/2017/10/Internet-in-China.html
- suvelx 6y agoIf this just leads to people releasing their JS libraries on some random unidentifiable domain (e.g. dx3nxk1hjdhy3.cloudfront.com ) then I think we're going to be in a worse position. I can presumably trust the code distributed by the 1st party, I can mostly trust code distributed by known CDNs, I cannot trust a randomized subdomain.
- Kagerjay 6y agoI agree with most of the author's statements, but there's some points that I like to add why you should use CDN's for javascript libraries. But you could always use a reputable CDN site, use a checksum for security, and if there is downtime issues, quickly revert and fix the issues on your end. CDN's are nice because it reduces the time to develop. I build a lot of startup apps and resort to CDN's, but if I were building a secure enterprise app this story would be different On another note of using CDN's, Deno is of interest. It's gaining popularity because it's using CDN's as part of it's pipeline dependency process. You don't have to waste a huge amount of time installing dependencies and node packages that you don't care for, just import and your done
- nedt 6y agoCDNs (can) do a bit more than just serving static files faster. For Javascript they can change the build for different group of browsers, sending less bytes to transmit parse. You could do that yourself, but learning build tools and using them correctly and keeping them up to date is not that easy.