Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery via Google CDN best practices

Tags:

jquery

cdn

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.

like image 561
Frankie Avatar asked Sep 28 '10 17:09

Frankie


People also ask

Should I use CDN for jQuery?

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.

What is the best CDN for jQuery?

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.

What is Google CDN jQuery?

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.

What is the advantage of hosting a jQuery using a CDN?

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.


1 Answers

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:

  1. Do we have the google version cached?
    • Yes - Ok good to go, use it.
    • No - Download it from Google, use it.
  2. Is jQuery (the JavaScript object) defined?
    • Yes - ok it loaded fine, the if() is false, continue on.
    • No - oh snap! Google load failed, either from cache or the fetch, need to load it from elsewhere
      • Load it from your site via a new <script> tag just added.
like image 115
Nick Craver Avatar answered Sep 30 '22 05:09

Nick Craver