6

I want to use Head JS to dynamically load all of the other scripts for my pages. I'm planning on using the version hosted by CDNJS to take advantage of the better caching, decreased latency, etc.

I have no reason to think CDNJS is going anywhere, but even for Google CDN hosted files like jQuery, I like to include a fallback. When I'm using jQuery though, the files are included at the end of the <body> tag. Due to the nature of Head JS, I need to include it in the <head> of my page.

In the <body> I would use two lines like this:

<script src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.96/head.min.js"></script>
<script> window.head || document.write('<script src="js/libs/head-0.96.min.js"><\/script>') </script>

Can I use this same set of lines in the head as a fallback? Won't document.write() overwrite my entire page? Don't scripts load differently when they exist in the <head> due to the order that browsers parse the DOM?

I'm still pretty new to this, so any guidance would be hugely helpful! Thanks!

stevenem
  • 63
  • 1
  • 6
  • 1
    document.write only destroys your document if you try doing it AFTER the page load has completed. An in-line document.write will execute as the page's loaded/parsed and simply insert the written data into the document as is. – Marc B Jul 20 '12 at 17:07
  • yes, but won't the Head JS load calls that are in the ` fire _before_ the script loads from a document.write? – stevenem Jul 20 '12 at 17:55
  • only if you marked the previous script tag as `async`. Otherwise scripts are loaded synchronously. – Marc B Jul 20 '12 at 18:40

1 Answers1

0

As you probably already know, you won't be testing for window.jQuery but some function included in head.js.

Additionally, you're right that you may not want to use document.write() twice here.

Instead of document.write(), try this:

function appendScript(url) {
  var head = document.getElementsByTagName('head')[0];
  var theScript = document.createElement('script');
  theScript.type = 'text/javascript';
  theScript.src = url;
  theScript.onreadystatechange = callback;
  theScript.onload = callback;
  head.appendChild(theScript);
}

For the url, use your local fallback.

Adam Grant
  • 12,477
  • 10
  • 58
  • 65
  • Thanks for pointing out the jQuery part! I'll give this one a shot! How to I set up the callback to run the `head.js()` commands after the Head JS is loaded? – stevenem Jul 20 '12 at 19:08
  • I'm not sure, I don't know much about head.js but I don't know if you could guarantee this would run before or after head.js by design. – Adam Grant Jul 20 '12 at 20:32