What is the purpose of this code:
<script>window.jQuery || document.write('<script src="jquery-1.11.3.min.js"><\/script>')</script>
as opposed to:
<script src="jquery-1.11.3.min.js"></script>
..when linking jquery to my html file.
This might be a stupid question. I'm new to web development. My jquery won't work when I use the first code. When I cut it down to the second code, it loads but it is glitchy. I have this code just before </body>
. Any help is greatly appreciated.
That line of code is usually used when you load jquery from a CDN, like
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery-1.11.3.min.js"><\/script>')</script>
The second script tag will check if window.jQuery is defined (which means the script was successfully loaded from the CDN). If not load a locally stored version.
The purpose of the first code piece is it checks if jQuery has been loaded or not. That is what
window.jQuery || ....
is saying. Either window.jQuery
exists OR do something else.
If window.jQuery
is undefined
, it will
document.write('<script src="jquery-1.11.3.min.js"><\/script>')
to load jQuery.
This can be useful when you dynamically load HTML content and you do not always need jQuery. If the order of events does not dictate exactly when you will need jQuery, you can explicilty load it when it is needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With