How to load javascript from CDN with local backup in <head>

I want to use Head JS to dynamically load all the other scripts for my pages. I plan to use the version hosted by CDNJS to use better caching, reduced latency, etc.

I have no reason to think CDNJS is going anywhere, but even for files hosted on Google CDN, such as jQuery, I like to include a backup. However, when I use jQuery, the files are included at the end of the tag <body>. Due to the nature of Head JS, I need to include it in <head>my page.

In <body>I would use two lines:

<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>

Is it possible to use the same set of lines in my head as a reserve? Won't document.write()rewrite my entire page? Are scripts loaded differently when they exist <head>because browsers parse the DOM?

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

+5
source share
1 answer

As you probably already know, you will not test window.jQuery, but some functions are included in head.js.

In addition, you are correct that you can not use document.write()twice here.

Instead, document.write()try the following:

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

Use a local reserve for the URL.

0

All Articles