javascript
  • refactoring
  • 2010-05-10 25 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它是容易出錯和阻塞。加載腳本後,您還可以選擇調用回調。

    相關問題