Why declare jQuery twice? [duplicate]
Solution 1:
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.
Solution 2:
It's trying to use the version hosted on Google's CDN first. There's a chance the person viewing the site already has that exact script cached from visiting some other site, so they might as well try that first.
If the CDN version loads, window.jQuery is set, the or is short-circuited, and the code moves on.
If the CDN version can't be loaded for some reason, it adds another script tag to the page pointing to a locally-hosted version of the script.
Edit: as MTCoster points out in a comment above, this trick relies on the way JavaScript is normally loaded. The browser pauses execution until the tag loads or times out. If jQuery were loaded asynchronously using the async attribute, this trick wouldn't work.