Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Loading jQuery from Google or locally if not online

Right now I have the following links in my code:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>

etc ...

I'd like to make use of the google.com cached copies. I heard google is the best source but please correct me if I am wrong.

Anyway is it possible for me to code my application so it uses code from google if available and locally if not. FYI I am using Microsoft MVC3 and the Msoft cloud servers.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, check out how they do it in HTML5 boilerplate.

If you take a look at the bottom of the index.html file within the GitHub repo, you'll see the following...

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/X.X.X/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="local/jquery-X.X.X.min.js">x3C/script>')</script>

NB: In the code snippet above X.X.X should be replaced with the jQuery version number that you're using (e.g. 1.8.2).

How does it work?

  1. First, an attempt is made to grab the CDN version (Google's CDN url is used above, but of course you could link to any source you like).
  2. Immediately afterwards, we check for the jQuery global object.
  3. If jQuery does not exist, the obvious assumption is that we didn't manage to get the code from the CDN, so then we document.write a script tag to get a copy from a local source instead.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...