javascript 動態指令碼添加的簡單方法_javascript技巧

來源:互聯網
上載者:User

非同步載入js檔案或者非同步載入js模組,支援所有瀏覽器,包括IE,參考至javascript進階編程

1.createScript方法用於建立一個script標籤並添加到body標籤中

2.createModule方法用於建立一個script指令碼的標籤,並且如果在IE8以下的版本運行會拋出異常,在異常捕獲模組中執行script.text相容IE添加js的指令碼內容。

<button id="demo">js檔案</button>  <button id="demo1">js模組</button>  <script type="text/javascript">    //非同步負載檔案,支援所有瀏覽器    document.getElementById("demo").onclick = function () {      createScript("../../js/jquery-1.8.3.min.js");    }    function createScript(url) {      var script = document.createElement("script");      script.type = "text/javascript";      script.src = url;      document.body.appendChild(script);    }    //這裡首先會嘗試標準的DOM方法,因為除了IE(在IE中會拋出錯誤),所有瀏覽器都支援這種方法,如果拋出錯誤則說明是IE,於是就必須使用tezt屬性了    document.getElementById("demo1").onclick = function () {      createModule("function sayHi(){alert('Hi !')}");    }    function createModule(code) {      var script = document.createElement("script");      script.type = "text/javascript";      try {        script.appendChild(document.createTextNode(code));      } catch (ex) {        script.text(code);      }      document.body.appendChild(script);    }  </script>

以上就是小編為大家帶來的javascript 動態指令碼添加的簡單方法全部內容了,希望大家多多支援雲棲社區~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.