selfthinker
selfthinker

Reputation: 554

How to add jQuery CDN fallback in XHTML?

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?

Upvotes: 3

Views: 1852

Answers (3)

selfthinker
selfthinker

Reputation: 554

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.

Upvotes: 0

Maksim Vi.
Maksim Vi.

Reputation: 9225

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);
}

Upvotes: 3

Quentin
Quentin

Reputation: 943220

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

Upvotes: 0

Related Questions