javascript
  • refactoring
  • 2010-05-10 39 views 3 likes 
    3

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

    回答

    5

    所有现代浏览器就会明白相对参考 URI格式,这将同时为httphttpsURI scheme names自动工作:

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

    延伸阅读:

    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它是容易出错和阻塞。加载脚本后,您还可以选择调用回调。

     相关问题

    • 暂无相关问题^_^