Learner One Learner One - 1 year ago 117
Javascript Question

Why declare jquery twice?

I tried for hours to make sense of this but it still unclear, can somebody help explain the purpose of this code, note that before the second script code below jquery.min.js is already included with googleapis.

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

Answer Source

It's to fallback to the jquery.min.js file stored on the same server when the cdn is down or cannot be reached.

It's essentially saying:

// 1. Try to download and run https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js

// 2. Was jQuery successfully loaded from the cdn? If so, it will be defined:
if (window.jQuery) {
    // Yes, it's defined. Good. Nothing more needed.
else {
    // No, it's not defined. Use my copy:
    document.write('<script src="/assets/js/vendor/jquery.min.js"><\/script>')

Read more here and you can find the original code here.

Regarding window.jQuery || document.write(...) that is essentially shorthand for the code above. When defined window.jQuery will be truthy and so the statement on the right hand side of || will not be executed; however, if it's not defined it will be falsy and the statement on the right hand side of || will be executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download