I'm loading jQuery via Google's CDN using the following code.
My main question is what will happen if a user hits my site and hasn't yet got jQuery pre-cached. Will he download the Google version and my own? How does concurrency here work?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
if(typeof jQuery == 'undefined') {
//<![CDATA[
document.write("<script src='/includes/jquery-1.4.2.min.js' type='text/javascript'><\/script>");
//]]>
}
</script>
Thanks.
There are a lot of people that say you should always use a CDN for libraries like jQuery (and other popular projects, as well). They say this for good reason. Using a CDN, as noted already, can reduce latency and allow browsers to cache a common file so it doesn't even have to load it from a server.
If you don't need HTTPS support, the fastest CDN is actually the official jQuery CDN, provided by Media Temple. Google's Libraries API CDN is a good second choice after that. If you need support for HTTPS, your best option is Google's Libraries API CDN.
Projects In JavaScript & JQueryGoogle provides CDN support for jQuery via the googleapis.com domain. The latest version of Google CDN provides four different types of jQuery versions- normal (uncompressed), minified, slim, and slim & minified. Google CDN provides the jQuery via ajax.googleapis.com domain.
This is because the jQuery file loads from a CDN and not from the website. In addition, jQuery loads faster when sourced from a CDN that it does when from the website. This is because CDNs will load jQuery files from the closest server to the user.
In your example code they will download the google version if they don't already have it because of another site. Then if for some reason google is down, they'll download your version, they won't download both. The second is only requested if the first (from Google) fails.
The check goes like this:
jQuery
(the JavaScript object) defined?
if()
is false, continue on.<script>
tag just added.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With