Should I link to Google API's cloud for JS libraries? - javascript

I'm looking for the pros/cons of pulling jQuery & other JS libraries from Google API's cloud as opposed to downloading files and deploying directly.
What say you?
My decision
The likelihood of the lib already cached on the users system is the overriding factor for me, so I'm going with a permalink to googleapis.com (e.g. ajax.googleapis.com/ajax/libs/…). I agree with others here that loss of access to the Google server cloud is a minimal concern.

Con
Users in countries embargoed by the U.S. (e.g. Iran) won't get a response from Google

Pros: It may already be cached on the user's system. Google has big pipes. You don't pay for the bandwidth.
Cons: You now have two different ways for your site to become unavailable: A service interruption on your server or one on Google's server.

I've been looking at the real-world performance of the Google loader for jQuery, particularly, and here's what I've found:
Google's servers are quick and plenty reliable.
They are serving from a CDN, which means if you have a lot of overseas users they'll get much better load times.
They are not serving gzipped files. So they're serving a lot more bytes than they need to.
If you know what you're doing in Apache, Lighttpd, or whatever you're serving files with, you could set your cache headers just like Google's and significantly reduce the amount of data your end user has to download by serving it from your own server. You could also combine your scripts at that point and reduce your overall HTTP requests.
Bottom line: Google's performance is good but not great. If you have many many overseas users then Google is probably better, if your users are mostly US-based and maximum performance is your concern, learn about caching, Etags, gzipping, etc. and serve it yourself.

Pros:
Google's connectivity is probably way better than yours
It's a free CDN (content distribution network)
Your webapp might load faster, since you're using a CDN
Cons:
If/when you need to optimize by repackaging a subset of that third-party JS library, you're on your own, and your webapp might then load slower

In addition to points made by others I'll point out two additional cons:
An additional external HTTP request, so assuming you have a Javascript file of your own (almost certain) that's two minimum instead of one minimum; and
IMHO because jQuery load is async your entire page can load before the library has loaded so the effects that you do on document ready are sometimes visibly noticeable to the user when they are applied. I think this is not a great user experience.

The pros are quite obvious and are in the other answers :
you save bandwidth
google is probably more reliable than your server
probably cached in most browsers (anyone stats on this ?)
But the cons can be very tricky :
If you are using https, you will get an error on most browsers as your certificate isn't valid for google's domain, only yours. This is a major issue for https.

I think what would be cool to do is run A/B tests and see what the latency is to load minified version of jquery from Google's servers vs your server. Hopefully that'll put things into perspective. Chances are the Google server might be faster, but in terms of accepting responsibility of down time, nothing beats hosting it yourself.

Pro:
Google's Ajaxlibs offer a very fine-grained "version control" for the included libraries. You can enforce a certain version (e.g. JQuery 1.3.2) or automatically request the latest version from a certain branch (e.g. JQuery 1.3 series -> would currently deliver 1.3.2, but maybe soon 1.3.3).
The later has definitely has benefits: you'll profit from smaller bugfixes/performance improvements without breaking your scripts/plugins.
Maintaining such a multi-library repository on your own can become quite ressource intensive.

Con:
When afraid of DNS poisoning, or when afraid that some public wireless network might not be trusted, then the non-SSL versions might actually not be served by Google at all, opening up drive-by installation of malware. (But: caching is set to be a full year, so even though many browsers will issue a If-Modified-Since request for cached content when hitting refresh, this might still be a theoretical issue as most users will already have cached the resources while using another network.)
When taking extreme care for your visitors' privacy, you might not want Google to record visits to your site by using their CDN. (Quite theoretical as well, as the same note on caching applies.)

Related

Lightweight JS Library vs Google-hosted CDN

When page-load speed is the priority, is it better to use a minimal, lightweight javascript library (hosted on a CDN), or is it better to use something like jQuery, hosted on Google's CDN that the browser more than likely already has loaded?
Edit: What my question really boils down to is whether the cross-site caching effect of using jQuery hosted on Google's CDN outweighs the benefits of using an ultra-light library, also on a CDN.
jQuery is not heavy as compared to any other javascript library at present looking at the amount of features and browsers it supports.
You can consider this factor while selecting the plugins to be used on the page because they are written by various users and some may right it intelligently considering this factor or some may just right it for the sake.
Yes, if you use CDN like Google for jQuery it is most likely that the library must be cached by the browser and also Google has number of servers based on location so you don't have to worry about it.
Decreased Latency
A CDN distributes your static content across servers in various, diverse physical locations. When a user’s browser resolves the URL for these files, their download will automatically target the closest available server in the network.
In the case of Google’s AJAX Libraries CDN, what this means is that any users not physically near your server will be able to download jQuery faster than if you force them to download it from your arbitrarily located server.
There are a handful of CDN services comparable to Google’s, but it’s hard to beat the price of free! This benefit alone could decide the issue, but there’s even more.
Increased parallelism
To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.
Using the Google AJAX Libraries CDN eliminates one request to your site, allowing more of your local content to downloaded in parallel. It doesn’t make a gigantic difference for users with a six concurrent connection browser, but for those still running a browser that only allows two, the difference is noticeable.
Better caching
Potentially the greatest benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all.
No matter how well optimized your site is, if you’re hosting jQuery locally then your users must download it at least once. Each of your users probably already has dozens of identical copies of jQuery in their browser’s cache, but those copies of jQuery are ignored when they visit your site.
However, when a browser sees references to CDN-hosted copies of jQuery, it understands that all of those references do refer to the exact same file. With all of these CDN references point to exactly the same URLs, the browser can trust that those files truly are identical and won't waste time re-requesting the file if it's already cached. Thus, the browser is able to use a single copy that's cached on-disk, regardless of which site the CDN references appear on.
This creates a potent "cross-site caching" effect which all sites using the CDN benefit from. Since Google's CDN serves the file with headers that attempt to cache the file for up to one year, this effect truly has amazing potential. With many thousands of the most trafficked sites on the Internet already using the Google CDN to serve jQuery, it's quite possible that many of your users will never make a single HTTP request for jQuery when they visit sites using the CDN.
Even if someone visits hundreds of sites using the same Google hosted version of jQuery, they will only need download it once!
It's better to use the library that best suits the needs of your application and your development team. A super-lightweight library might save you a few hundred milliseconds of load time, but may end up costing you in development hours if your team has significantly more experience with jQuery/MooTools/Dojo etc.
If new feature implementation and bug fixing is hindered by using a second-rate tool solely to improve load times, your users are ultimately going to suffer.

Serve jQuery UI from Google's CDN or as a local copy?

while it's better to serve jQuery from Google's CDN jQuery UI is a different beast. My local modified copy weighs 60kb and the one in Google's CDN ~200kb.
Are there any numbers on how many sites uses the CDN? (read: how many users have it in their cache). How do I know/calculate if it's better to serve it locally?
Coming late to the party here, but allowing for gzip compression, you're basically comparing a download of ~51k from Google's CDN (the 197.14k content becomes 51.30k on-the-wire) vs. ~15.5k from your own servers (assuming your 60k file gzips at the same ratio as the full jQuery UI file does, and that you have gzip compression enabled). This takes us into a complex realm of:
pre-existing cache copy
latency
transfer time
number of requests
proper cache headers
And the answer to your question is a big: It depends, try each of them and measure the result in a real world scenario.
Pre-Existing Cache Copy
If a first-time visitor to your site has previously been to a site using jQuery UI from Google's CDN and it's still in their cache, that wins hands down. Full stop. No need to think about it any further. Google uses appropriate caching headers and the browser doesn't even have to send the request to the server, provided you link to a fully-specified version of jQuery UI (not one of the "any version of 1.8.x is fine" URLs — if you ask for jQuery UI 1.8.16, Google will return a resource that can be cached for up to a year, but if you ask for jQuery UI 1.8.x [e.g., any dot rev of 1.8], that resource is only good for an hour).
But let's suppose they haven't...
Latency and Transfer Time
Latency is how long it takes to set up the connection to the server, and transfer time is the time actually spent transferring the resource. Using my DSL connection (I'm not very close to my exchange, so I typically get about 4Mbit throughput on downloads; e.g., it's an okay connection, but nothing like what Londoners get, or those lucky FiOS people in the States), in repeated experiments downloading Google's copy of jQuery UI I typically spend ~50ms waiting for the connection (latency) and then 73ms doing data transfer (SSL would change that profile, but I'm assuming a non-SSL site here). Compare that with downloading Google's copy of jQuery itself (89.52k gzipped to 31.74k), which has the same ~50ms latency followed by ~45ms of downloading. Note how the download time is proportional to the size of the resource (31.74k / 51.30k = 0.61871345, and sure enough, 73ms x 0.61871345 = 45ms), but the latency is constant. So assuming your copy comes in at 15.5k, you could expect (for me) a 50ms latency plus about 22ms of actual downloading. All other things being equal, by hosting your own 60k copy vs. Google's 200k copy, you would save me a whopping 52ms. Let's just say that I wouldn't notice the difference.
All is not equal, however. Google's CDN is highly optimized, location-aware, and very fast indeed. For instance, let's compare downloading jQuery from Heroku.com. I chose them because they're smart people running a significant hosting business (currently using the AWS stack), and so you can expect they've at least spent some time optimizing their delivery of static content — and it happens they use a local copy of jQuery for their website; and they're in the U.S. (you'll see why in a moment). If I download jQuery from them (shockingly, they don't appear to have gzip enabled!), the latency is consistently in the 135ms range (with occasional outliers). That's consistently 2.7 times as much latency as to Google's CDN (and my throughput from them is slower, too, roughly half the speed; perhaps they only use AWS instances in the U.S., and since I'm in the UK I'm further away from them).
The point here being that latency may well wash out any benefit you get from the smaller file size.
Number of Requests
If you have any JavaScript files you're going to host locally, your users are still going to have to get those. Say you have 100k of your own script for your site. If you use Google's CDN, your users have to get 200k of jQuery UI from Google and 100k of your script from you. The browser may put those requests in parallel (barring your using async or defer on your script tags, the browser has to execute the scripts in strict document order, but that doesn't mean it can't download them in parallel). Or it may well not.
As we've established that for non-mobile users, at these sizes the actual data transfer time doesn't really matter that much, you may find that taking your local jQuery UI file and combining it with your own script, thus requiring only one download rather than two, may be more efficient even despite the Google CDN goodness.
This is the old "At most one HTML file, one CSS file, and one JavaScript file" rule. Minimizing HTTP requests is a Good ThingTM. Similarly, if you can use sprites rather than individual images for various things, that helps keep image requests down.
Proper Cache Headers
If you're hosting your own script, you'll want to be absolutely sure it's cacheable, which means paying attention to the cache headers. Google's CDN basically doesn't trust HTTP/1.0 caches (it sets the Expires header to the current date/time), but does trust HTTP/1.1 caches — the overwhelming majority — because it sends a max-age header (of a year for fully-specified resources). I'm guessing they have a reason for that, you might consider following suit.
Since you want to change your own scripts sometimes, you'll want to put a version number on them, e.g. "my-nifty-script-1.js" and then "my-nifty-script-2.js", etc. That's so you can set long max-age headers, but know that when you update your script, your users will get the new one. (This goes for CSS files, too.) Do not use the query string for the versioning, put the number actually in the resource name.
Since your HTML presumably changes regularly, you probably want short expirations on that, but of course it totally depends on your content.
Conclusion
It depends. If you don't want to combine your script with your local copy of jQuery UI, you're probably better off using Google for jQuery UI. If you're happy to combine them, you'll want to do real-world experiments either way to make your own decision. It's entirely possible other factors will wash this out and it won't really matter. If you haven't already, it's worth reviewing Yahoo's and Google's website speed advice pages:
Yahoo! Best Practices for Speeding Up Your Website
Google's Let's make the web faster site
Google's CDN of jquery UI weighs in at 51 Kb:
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
The HTML5 Boilerplate uses a fallback for jquery loading:
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>
You can apply it to jquery ui:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script>window.jQuery.ui || document.write('<script src="js/jquery-ui-1.8.16.min.js">\x3C/script>')</script>
You load the CDN version then check for the existence of jquery ui (you can't guarantee 100% up-time for any CDN). If jquery ui doesn't exist, fall back to your local. In this way, if they have it already in their cache, you are good to go. If they don't and the CDN can't be retrieved for any reason, your good to go with your local. Fail safe.
I think size comparisons miss the point of the CDN. By serving a copy of jQuery (or other library) from a public, commonly-used CDN, many users will have a cached copy of the library before they arrive at your site. When they do, the effective size of the download is 0KB compared to 60KB from your server.
Google's CDN is the most widely used, so you will have the best chance of a cache hit if you reference it.
For numbers comparing the various CDNs please see this article.
For what it's worth, the minified version of Google's jQuery copy is much smaller than the size you mentioned.
I would say what matter is the load you have on your server. For the user it doesn't really matter if they are downloading it from your server or from google's server. These days there is enough bandwidth for 140kb to be easy to ignore on the user's side.
Now the really question is if you made changes to jQuery UI. If yes then you should serve your own copy. If not, then it's ok to serve google's. Because after all what you are aiming to is to lower load on your side.
And besides the caching doesn't happen just on the user's browser, but also on content distribution nodes that they are accessing. So it's safe to say that google's copy is cached almost for sure.
With sizes this small, what matters is number of http requests for a first-time visitor to your site.
If for example your site has script combining and minification configured so the entire script for a first time visitor is either one request or included in html itself, using your local copy is better because even a cached copy of JqueryUI isn't faster than all the script for the site showing up at once (the cached call still has to go out and check for Modified).
If you don't have a good script combining and minification setup (so you were going to send jqueryui separately, either from your site or elsewhere), use outside caches wherever possible.

Hosted javascript libraries

Besides Google Libraries API what other services are there for hosted javascript libraries?
Please only list trusted sources, not some unknown third party.
Microsofts CDN
http://www.asp.net/ajaxlibrary/cdn.ashx
Before you go in search of hosted JavaScript libraries, you should consider the fact that any JavaScript that you include in your web page runs within the context of your domain and can access any data rendered on the web page or that the user can normally access on your domain. Using Google's hosted JavaScript is fine, but if its some third party you never have heard of, you might want to think twice.
Perhaps it would be better to search for high-quality JavaScript libraries and download your own copy that you maintain within your domain on your own servers (and can audit for security purposes)?
Out of curiosity... what specific functionality are you looking for?
There's also Yahoo YUI (http://developer.yahoo.com/yui/) though I believe they only host YUI itself. Make sure you pay attention to Michael Safyan's answer, too - who you're willing to trust with your users' code should be a carefully made decision. Beyond that, if you're looking for generic JS hosting you should make sure you really need it - a minified version of jQuery or MooTools is incredibly tiny, and shouldn't make any real difference either to your server's CPU usage or bandwidth expenditure.
It also doesn't meaningfully affect the maintainability of your HTML or JS, and it introduces another point of failure in your implementation.

Benefits vs. Pitfalls of hosting jQuery locally [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
We're currently pulling jQuery and jQueryUI (and jQueryUI CSS) libraries from the google CDN. I like this because I can call google.load("jquery", "1");
and the latest jQuery 1.x.x will be used.
Now I am to pull the libraries locally because of security.
I'm happy to pull them locally but I'm wondering what are some of the other benefits and pitfalls to watch out for?
I always use the CDN (Content Delivery Network) from Google. But just in case it's offline:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="jquery-1.4.2.min.js"><\/script>')</script>
Grab Google CDN's jQuery and fallback to local if necessary
Edit:
If you don't need to support IE6 and your site has partial https usage you can remove the http as well:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
The main benefit of having them on a CDN is that the files can be downloaded in parallel to files downloaded from your own website. This reduces latency on every page. So, the flip side of this is a pitfall of hosting locally - increased latency. The main reason for that is that browsers are limited in the number of connections that they can make at the same time to the same web domain. In IE6 this was defaulted to 2 concurrent connections to the same domain - shared between all open windows of IE!! In IE8+ it improved, defaulting to 6, which is inline with FF/Chrome, but still, if you have a lot of images and you are not using sprites, you will experience heavy latency.
Using a CDN, I would always set the library version explicitly rather than getting the latest one. This reduces the risk of new versions breaking your code. Not very likely with jQuery, but possible.
The other main benefit of using a CDN is reduced traffic on your site. If you pay per GB or you are on a virtual server with limited resources, you might find that overall site performance increases and hosting costs come down when you farm off some of your content to a public CDN.
Make sure you also read the other answer to this question by #Xaver. This is a very good trick
Others have covered the benefits. Pitfalls:
If you only include content from your own server, that's one server that needs to be running—and not blocked by firewalls etc—to make your site work. Pull script from a third party and now that's two servers that need to be running and unblocked to make your site work.
Any site you pull <script> from can completely control the user's experience on your site. If Google were feeling evil they could put something in their copy of jQuery to log your keypresses, steal personal information from the page you're on to tie into their web tracking database, make you post “I love Google!” comments to every form, and so on.
Google probably aren't actually going to do that, but it's a factor that's out of your control, and certainly something to worry about with other script-hosting services. There have been incidents before where stats scripts have been compromised with malware loaders.
Before including any script from a third party—even on one single page of your site—you must 100% trust them with all user-accessible functionality visible on that hostname (including web-facing admin functions).
Google CDN:
caching, good for performance, more users likely to have it already, and it downloads in parallel
if ever, heaver forbid cdn goes down. you're screwed.
if a new version breaks your existing plugins or site, you'll know about it possibly too late
Locally:
development without being connected to the net is possible
can still get some performance benefits by gzipping, in addition to minifying
I prefer to use my local version, because I don't have control about what they will provide.
For example I don't want my users to get affected by google-analytics or anything similar, because this is a legal problem in my country.
Benefits: (Specifically for Google's CDN)
Downloads in parallel with your files. Other answers address this further
Google's Servers are likely to be able to physically deliver the content faster
Common libraries and frameworks might already be on the user's machine, as the HTTP cache for a CDN is universal across all sites
Your bandwidth wouldn't have to go towards serving large library files
Virtually every way you look at it, using Google's CDN is a good thing.
Performance will be improved (albeit fairly marginally, unless your site is really busy), and the amount of data your servers have to transmit will go down (although jQuery isn't exactly a massive thing to download), etc.
The only reason you wouldn't want to use it is if you don't trust Google. By using it, you are effectively giving Google an additional window of information into your site's traffic profile, including knowledge of URLs that you may otherwise not want to make public (eg secure areas of your site).
If you are paranoid about security then this may be enough to persuade you not to use them (after all, hosting it yourself isn't exactly going to slow your site down to a crawl), but in general most people would take the pragmatic view that Google knows enough about their site already that adding this won't make much difference.
Probably I'm in minority nowadays, but I'd say that you don't want to use CDN unless you really need to. Key factors to start using it are:
Cross geo users. If you host your website in the US but have visible amount of European users - CDN will improve the loading time.
Big amount of users and\or big content, so one main server is not enough any more. One can think of any porn-video website (or Netflix, if you want). Video stream is a heavy load, with CDN would be much much less load on the main server.
But... the point is that these points are not really applicable to 90% of websites in the world. I bet you're not Facebook with millions of online users around the globe, you're not Pornhub with hundreds of GB transferred every second.
If your website is targeted to users in your city/country and capacity of one server is enough for amount of users you have - why would you ever want a CDN? It's quicker for your users in your city and simpler for you to fetch everything from your main server locally.
It was more about CDNs in general, now let me be closer to the actual question about jQuery or any other library.
If you want your website to stay accessible and working without maintenance for more than a year, let's say - put it locally. Libraries nowadays are being updated in a crazy tempo which you probably don't want to follow. And old versions are being deleted eventually. Moreover, the whole library can die (probably not applicable to jQuery though).
From my recent experience - I updated TinyMCE on the website I maintain from 3.x.x (dated 2012) to 5.x.x (dated Spring 2019). This website was working for 7(seven!) years without any maintenance in this part of the logic. There was no "minifying" concept back then and CDNs were not as common as now. But even if they would be common - you never know what will happen in 3-5-10 years from now. Usually you want your website to stay alive even without you maintaining it, don't you? However if you pull jQuery from CDN today, then this link may (and, probably, will) break in 5 years.
Solution with CDN AND fallback to local version as #Xaver suggested can be a good compromise. But... maybe just get rid of CDN link? ;)
To me it really depends on how much control you desire to have. If you are like me and need to develop on local host when working and traveling. Having the jquery files local is better than having it hosted on google or else where.

Should I place Jquery files on my web server or just refer to them via jquery.com in my PHP files, which is better?

When I use Jquery or its plugin, should I just add
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
Or should I download both files and upload both to my web server so my web server can fetch both files locally? Which is better and why?
Better than that, let Google host them for you. See What is the AJAX Libraries API?. You can load them asynchronously or just reference the static files.
For example:
http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
Whereas Google has offered this service so it's fine to use it, I'm not sure jQuery has so unless someone explicitly says "you can link stuff from my site" you should err on the side of caution and not (potentially) steal their bandwidth.
I know it's a bit silly but, if you go for external host, just make sure you will never need to show your website anywhere that doesn't have a internet connection.
It's pretty unusual but hapenned to me once. I dad to show a new version of an already running site to a client in a presentation room with no internet.
Another case is an intranet site. If internet is down nobody will be able to connect to the intranet because it has a link to google .js or somewhere else.
:D
There are valid arguments for both hosting your jQuery files locally or externally (usually via google).
The major argument against linking from an external server is that you're adding another point of failure to your website, but then again, google doesn't go down very often.
The argument in favor is a slight performance boost due to the fact that google uses a CDN for their files and that external files can be downloaded in parallel. Here's a great article that makes the case for this setup.
If you're not sure, try downloading FireBug and check to see what kind (if any) of a performance boost you get.
Another thought to consider (depending on the audience of your site) is your bandwidth cost. If you have to send file(s) to a huge number of clients, it can add up. Someone else (like Google) hosting that means that they're dealing with that, and not you.
Something different, if you have a lot of loose JS files (jQuery plugins?), then you could also consider minifying and merging them all into a single file on your host with a far-future expire time and gzip encoding. This saves lengthy (external) requests. Minifying and merging can easily be automated before deploy or during server startup.
Aside from an external dependency and yet another point of failure, per Chris' point, referencing files at a different domain means more DNS lookups. Merging files (where possible) and minifying also improves performance, as BalusC mentioned. Lots of good information can be found at http://developer.yahoo.com/performance/rules.html and there are a lot of very helpful tools available as well some of which follow:
http://developer.yahoo.com/yslow/
http://www.webpagetest.org/
http://code.google.com/speed/page-speed/
http://getfirebug.com/

Categories

Resources