views:

68

answers:

2

I have the following script tags in the <head> so that they don't prompt any security errors when going back and forth between SSL and non-SSL pages. But it just looks hairy.

Any way I can combine them or reduce some of the code?

<script type="text/javascript">document.write(["\<script src='",("https:" == document.location.protocol) ? "https://" : "http://","ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript'>\<\/script>"].join(''));</script>
<script type="text/javascript">document.write(["\<script src='",("https:" == document.location.protocol) ? "https://" : "http://","html5shiv.googlecode.com/svn/trunk/html5.js' type='text/javascript'>\<\/script>"].join(''));</script>
<script type="text/javascript">document.write(["\<script src='",("https:" == document.location.protocol) ? "https://" : "http://","use.typekit.com/12345.js' type='text/javascript'>\<\/script>"].join(''));</script>
+5  A: 

All modern browsers will understand the Relative Reference URI format, which will work automatically for both the http and https URI scheme names:

<script src="//example.com/path/script.js"></script>

Further reading:

Daniel Vassallo
A: 
<script type="text/javascript">
  // Create a closure for our loadScript-function
  var loadScript = (function () {
       var headTag = document.getElementsByTagName('head')[0],
           scriptTagTemplate = document.createElement('script'),
           addEventListener = function (type, element, listener) {
              if(element.addEventListener) {
                 element.addEventListener(type, listener);
                 return true;
              }
              else if (element.attachEvent) {
                 element.attachEvent('on'+type, listener);
                 return true;
              }
              return false;
           };
       scriptTagTemplate.type = 'text/javascript';

       // This function clones the script template element and appends it to head
       // It takes an uri on the form www.example.com/path, and an optional
       // callback to invoke when the resource is loaded.
       return function (uri, callback) {
          var scriptTag = scriptTagTemplate.cloneNode(true);
          if (callback) {
              addEventListener('load', scriptTag, callback);
          }
          headTag.appendChild(scriptTag);
          scriptTag.src = ['//', uri].join('');
       }
    }());
</script>

Now you can use the function like so:

<script>
        loadScript('ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
        loadScript('html5shiv.googlecode.com/svn/trunk/html5.js');
        loadScript('use.typekit.com/12345.js');
</script>

The strength of this solution is that you avoid using document.write which is error-prone and blocking. You also get an option to have a callback invoked once the script is loaded.

PatrikAkerstrand