How does HTML5 Boilerplate jQuery library fallback work?

柔情痞子 提交于 2019-12-01 11:40:16

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18173272/how-does-html5-boilerplate-jquery-library-fallback-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!