Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare jQuery twice? [duplicate]

What is the purpose of the following 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> 
like image 636
Learner One Avatar asked Apr 27 '16 02:04

Learner One


People also ask

What happens if a click event is run twice?

happens to be run twice, you will have two identical click events bound, and the action will happen twice. I have that code in the document.ready function. I don't believe it is being bound twice. I put an alert before the findNearbyLocations call and it only gets called once each time for the first and subsequent clicks.

Is it possible to have multiple ID's in a jQuery page?

It's not supposed to be allowed to have a duplicate ID, but JQuery copes with it and will run the event for each of them. @Spudley, afraid not. It's an empty webpage with the basic html/head/body tags, and a user control. No other elements. The user control just contains the one button and a div to dump the results in.

How to prevent the findstores() function from being called twice?

In that case you could simply set a flag when the success method is called and not allow the findStores function to be called a 2nd time. Whenever I have found this happening, it's because I accidentally bound the event to the control twice.


1 Answers

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.

like image 51
David Sherret Avatar answered Sep 21 '22 03:09

David Sherret