8

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.

Frankie
  • 24,627
  • 10
  • 79
  • 121
  • 1
    One question I would have is why have your second check anyway? If Google is down, I'm pretty sure most of the internet is going down with it...(I'm only half-joking). Is the redundancy really necessary? – JasCav Sep 28 '10 at 17:08
  • 1
    @JasCav - There is, however small a chance, that the user can't access `google.com`, maybe in China perhaps? Just an example off the top of my head. – Nick Craver Sep 28 '10 at 17:11
  • @JasCav: One client once couldn't access the script on Google. I don't know the exactly reason, but it's better to prevent, a couple of lines more won't hurt. – BrunoLM Sep 28 '10 at 17:14
  • @Nick @BrunoLM - Okay. Good points. Now that I think about it, I once ran into a similar situation. Thanks. – JasCav Sep 28 '10 at 17:29
  • 1
    @JasCav I would probably go as far as to say that if Google is down no one in that area will discover my site. But as long as their are already a regular to it... no reason to let Google drag me down on the shortages (even Google!) has on some specific network points from time to time. – Frankie Sep 28 '10 at 19:22

1 Answers1

9

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.
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155