簡體   English   中英

我該如何重構這些腳本標簽?

[英]How can I refactor these script tags?

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

所有現代瀏覽器都將理解相對引用 URI格式,該格式將自動用於httphttps URI方案名稱

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

進一步閱讀:

<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 您還可以選擇在加載腳本后調用回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM