Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I link my jquery inside a document.write?

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.

like image 447
Jason Carrick Avatar asked May 17 '15 04:05

Jason Carrick


2 Answers

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.

like image 162
lagerone Avatar answered Nov 15 '22 20:11

lagerone


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.

like image 33
AmmarCSE Avatar answered Nov 15 '22 21:11

AmmarCSE