CDN's
are great but they may go down once in a while for minutes or hours and will disrupt your website from loading properly or may not load at all. So it is better to have a quick and efficient fallback solution as your failsafe.
<script type="text/javascript">
if (typeof jQuery === 'undefined') {
var e = document.createElement('script');
e.src = '/local/jquery-2.0.min.js';
e.type='text/javascript';
document.getElementsByTagName("head")[0].appendChild(e);
}
</script>
It should be well noted however that the above approach does not "defer" execution of other script loading (such as jQuery plugins) or script-execution (such as inline JavaScript) until after jQuery has fully loaded. Because the fallbacks rely on appending script tags, further script tags after it in the markup would load/execute immediately and not wait for the local jQuery to load, which could cause dependency errors.
A solution for that is to use document.write()
and by doing so
you will block other JavaScript included lower in the page from loading and executing.
as in :
<script type="text/javascript">
if (typeof jQuery === 'undefined')
document.write('<script type="text/javascript" src="/local/jquery-2.0.min.js"><\/script>');
</script>
In your code :
‘||’ is essentially acting as an OR statement. If ‘window.jQuery
’ returns FALSE (in other words, if the jQuery
was not successfully loaded), then it executes the next statement – adding a script tag to the page that references your local copy of the library.
EDIT: Explanation to the code used in the question.