0
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

Here is my current code. Is there any way to load a local copy of the jquery lib, if script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" fails? And is this script loaded asynchronous? Or will it freeze the ui thread until loaded?

1

1 Answer 1

4

You can just do this:

<script src="cdn.jquery.js"></script>
<script>window.jQuery || document.write('<script src="/local/jquery.js"><\/script>')</script>
Sign up to request clarification or add additional context in comments.

9 Comments

doesnt IE throw an exception when jQuery is undefined?
My problem is that sometimes jquery is already loaded, regardless of if the user is connected to the internet. Could i add another ||? Something like this: <script>window.jQuery || document.write('<script src="code.jquery.com/jquery-latest.js"><\/script>||document.write('<script src="/local/jquery.js"><\/script>')</script>
Just load it before that snippet and if it fails then it will load the local version. See my edit.
But now it will load <script src="cdn.jquery.js"></script> even if another version is already loaded, right?
You mean if the script is loaded in cache?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.