3

It is good practice to load a CDN-hosted jQuery but to fallback to a local file. E.g. HTML5 Boilerplate does it like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.0.min.js"><\/script>')</script> 

But how can the same be implemented in XHTML? As document.write() doesn't work in proper XHTML (sent as application/xhtml+xml), is there an alternative?

0

3 Answers 3

3

This code creates a new <script/> element and appends it before first <script/> element on your page:

if (!window.jQuery) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'js/vendor/jquery-1.8.0.min.js'; var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); } 
Sign up to request clarification or add additional context in comments.

Comments

0

createElement, setAttribute, appendChild as per usual when replacing document.write or innerHTML

Comments

0

Expanding on Maxim Vi.'s reply, I made it closer to the original idea to insert it where it is called:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type="text/javascript" id="jQuery"> if (!window.jQuery) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = '/js/jquery-1.8.0.min.js'; var jQueryScript = document.getElementById('jQuery'); jQueryScript.parentNode.insertBefore(script, jQueryScript); } </script> 

This way you can keep your scripts in the footer (in case you have other scripts inside the page, it won't get inserted too early or in different locations).

Edit: I had problems in some browsers with that solution, but moving the id="jQuery" further down solved it. I adjusted the code accordingly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.