4

I want to load jQuery with a fallback solution and have come across two different solutions:

1:

<script src="//ajax.googleapis.com/ [...] jquery.js"></script>
<script> window.jQuery || document.write('<script src="js/jquery.js"><\/script>') </script>

2:

<script src="//ajax.googleapis.com/ [...] jquery.js"></script>
<script> if ( typeof jQuery == "undefined" ) document.write('<script src="js/jquery.js"><\/script>') </script>

What's the difference between these snippets and which solution would be the preferred one?

user2864740
  • 60,010
  • 15
  • 145
  • 220
moosebag
  • 53
  • 1
  • 5
  • 1
    Effectively nothing (although there are minor differences) and, the former (as my personal preference). – user2864740 Oct 13 '14 at 09:42
  • They both do the same thing. If `window.jQuery` is not present, inject an alternate URL for jQuery. The first is a common pattern in JS code (if something is missing/undefined evaluate the expression on the right instead). – iCollect.it Ltd Oct 13 '14 at 09:42
  • No differences, same result – Oscar Oct 13 '14 at 09:43
  • Also http://stackoverflow.com/questions/16611971/is-it-necessary-to-use-the-typeof-operator-to-check-if-a-variable-exists-in-ja?lq=1 (question covers same context but answer is non-informative) , http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript?lq=1 (but question/answers do not focus on properties..) The `x || ..` vs `if (x) { .. }` is another issue. – user2864740 Oct 13 '14 at 10:00

2 Answers2

2

Both will perform the same action the only difference is that the former will execute faster than the latter.

That's why former is the preferred way.

Robert
  • 5,278
  • 43
  • 65
  • 115
kshitij
  • 578
  • 3
  • 9
0

There is no different between them. Just first one is more professional. you can do it in this way too:

<script> if (window.jQuery) document.write('<script src="js/jquery.js"><\/script>') </script>
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
  • `Professional` ? How can a problem be solved by Professional way correctly if there is Unprofessional way? – Pratik Joshi Oct 13 '14 at 09:44
  • 1
    While I wouldn't say the using typeof is "less professional", I would say that it's mostly used due to muscle memory and propagation of "this worked" more than an actual understanding of why it is used and/or needed on bare identifiers. (Why people still use `typeof x === 'undefined'` on a local variable or a property is beyond me.) – user2864740 Oct 13 '14 at 09:46
  • I think both forms about equally as "easy" to understand .. in any case there *is* a subtle difference between the forms. This has been covered too many times before. – user2864740 Oct 13 '14 at 09:47