我该如何重构这些脚本标签?

时间:2010-05-10 19:59:07

标签: javascript refactoring

我在<head>中有以下脚本标记,以便在SSL和非SSL页面之间来回切换时不会出现任何安全错误。但它看起来很毛茸茸。

我可以将它们组合起来或减少一些代码吗?

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

2 个答案:

答案 0 :(得分:5)

所有现代浏览器都会理解相对参考 URI格式,该格式将自动适用于httphttps URI scheme names

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

进一步阅读:

答案 1 :(得分:0)

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

现在你可以使用这样的功能:

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

此解决方案的优势在于您可以避免使用容易出错且阻塞的document.write。您还可以选择在加载脚本后调用回调。