Search code examples
javascriptjqueryperformancedocument.write

Is there any reason one would use document.write() to include jquery cdn?


I'm working on some possible add-on modules for an open-source project, written in php. I'm puzzled by the code I'm finding in the html header, but I'm reasonably new to working with anything other than html and css.

<script type="text/javascript">window.jQuery || document.write(unescape('%3Cscript type="text/javascript" src="//code.jquery.com/jquery-1.12.0.min.js"%3E%3C/script%3E'));</script>
<script type="text/javascript">window.jQuery || document.write(unescape('%3Cscript type="text/javascript" src="<?php echo $template->get_template_dir('.js',DIR_WS_TEMPLATE, $current_page_base,'jscript'); ?>/jquery.min.js"%3E%3C/script%3E'));</script>

The closest answer I found to why they are adding it twice is that the local copy is a fallback in case the CDN is overloaded. Force Download from local cache

But even in that case, wouldn't the main, top link be:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"> </script>

... and then if anything was to be included via document.write(), it would be the fallback?

It's also throwing up error warnings in the developer console. I'm asking if there is some sort of reason (that I wouldn't understand yet) for doing it the way they're doing it. If I replace the two lines of document.write() stuff with the direct link, I don't get console warnings, and my project seems to load much faster.


Solution

  • The reason document.write is used to load the script tag is because of the window.jQuery || bit just beforehand. Using the || operator like this checks to see if the left-hand expression is defined - if so, it does nothing; if not, it runs the expression on the right-hand side, which creates the script tag. This creates the ability to load jQuery only if it hasn't been loaded on the page already.