javascript動態載入js指令碼
1、直接document.write
代碼如下 |
複製代碼 |
<script language="javascript"> document.write("<script src='test.js'></script>"); </script> |
2、動態改變已有script的src屬性
代碼如下 |
複製代碼 |
<script src='' id="s1"></script> <script language="javascript"> s1.src="test.js" </script> |
3、動態建立script元素
代碼如下 |
複製代碼 |
function require(url, options){ var head, node, isOpera; isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]'; options.success = options.success || function(){}; options.error = options.error || function(){}; options.type = options.type || 'text/javascript'; options.charset = options.charset || 'utf-8'; options.async = options.async || true; head = document.getElementsByTagName("head")[0]; node = document.createElement(//javascript/i.test(options.type) ? 'script' : 'style'); node.type = options.type; node.charset = options.charset; node.async = options.async; node.src = url; if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera){ node.attachEvent('onreadystatechange', function(){ if(!node.readyState || node.readyState == "loaded" || node.readyState == "complete"){ options.success(); } }); }else{ node.addEventListener('load', options.success, false); node.addEventListener('error', options.error, false); } head.appendChild(node); } |
IE不支援載入失敗檢測
代碼如下 |
複製代碼 |
require('http://code.jquery.com/jquery-1.7.3.min.js', { success:function(){ alert('jquery loaded!'); }, error:function(){ alert('jquery load fail!'); } }); |
方法四
代碼如下 |
複製代碼 |
//動態載入指令檔 function AddScript(scriptID,scriptSRC) { if(document.getElementByIdx(scriptID)!=null) return; var Heads = document.getElementsByTagName_r("HEAD"); if(Heads.length==0) return; var oHead = Heads.item(0); var oScript= document.createElement("script"); oScript.id = scriptID; oScript.type = "text/javascript"; //oScript.text = scriptContent; oScript.src = scriptSRC; oHead.appendChild(oScript); } //動態載入指令碼內容 function AddScript(scriptID,scriptContent) { if(document.getElementByIdx(scriptID)!=null) return; var Heads = document.getElementsByTagName_r("HEAD"); if(Heads.length==0) return; var oHead = Heads.item(0); var oScript= document.createElement("script"); oScript.id = scriptID; oScript.type = "text/javascript"; oScript.text = scriptContent; oHead.appendChild(oScript); } |