tags:

views:

57

answers:

1

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"&gt;&lt;/script&gt;
<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.

+5  A: 

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
@Nick, perfect. Love your style of answering. Exactly what I was aiming for. Thanks.
Frankie