开发者

jQuery via Google CDN best practices

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/j开发者_如何转开发query-1.4.2.min.js' type='text/javascript'><\/script>");
        //]]>
    }
</script>

Thanks.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜