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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Johan
  • 35,120
  • 54
  • 178
  • 293

1 Answers1

4

You can just do this:

<script src="cdn.jquery.js"></script>
<script>window.jQuery || document.write('<script src="/local/jquery.js"><\/script>')</script>
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • doesnt IE throw an exception when jQuery is undefined? – Johan Sep 18 '12 at 10:17
  • 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: `` – Johan Sep 18 '12 at 10:20
  • Just load it before that snippet and if it fails then it will load the local version. See my edit. – elclanrs Sep 18 '12 at 10:21
  • But now it will load `` even if another version is already loaded, right? – Johan Sep 18 '12 at 10:23
  • You mean if the script is loaded in cache? – elclanrs Sep 18 '12 at 10:24
  • Im trying to make a fix for a page that adds usercontrols to some pages. And if a certain usercontrol is added, jquery is included in that. So sometimes it will be loaded twice, which results in some errors. Sorry for beeing unclear – Johan Sep 18 '12 at 10:25
  • Why not just load jQuery in the head? I don't get it... Otherwise consider using AMD modules. – elclanrs Sep 18 '12 at 10:28
  • Some designer prefered to load all scripts at the bottom of the page. But ill try to move em. Thanks – Johan Sep 18 '12 at 10:29
  • Bottom of the page is fine too just wrap everything in DOM ready in that case – elclanrs Sep 18 '12 at 10:30