Question

This is a beginner question to html5 boilerplate, and javascript in general, but I can't seem to find the answer anywhere, so here it goes...

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

How does the second script line checks whether the google's CDN has been loaded or not? There's no if statement or anything to suggest that. I'm sorry if this sounds stupid. Any help?

Was it helpful?

Solution

The || is the if statement in this case. If window.jQuery returns TRUE, then anything after the or statement (||) won't get loaded. If it's FALSE, then it'll continue on to load jquery.

Edit: Just to clarify a bit. If you do if (var1 && var2) in javascript, it'll evaluate BOTH variables to check if they're both true. If you make it if (var1 || var2), then if the first variable evaluates to TRUE, there's no need to evaluate the rest of the expression, since it'll automatically be true either way.

In this case, that's exactly what your code is doing. If window.jQuery is FALSE (meaning jQuery wasn't loaded), then continue on and evaluate the next expression--which in this case loads the jquery from a local file. It's just not wrapped in an IF statement since it's not necessary.

OTHER TIPS

If jQuery file from google CDN or anywhere is loaded, it would have been added a property jQuery to window object. Second line of your script checks if window.jQuery is defined or not, if not it executes the other part of || statement which adds a script tag having local jQuery file location src attribute to load it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top