2009-09-03 54 views

回答

14

這是一種方式:

function loadDaFun() { 
    var script = document.createElement('script'); 
    script.src = '/path/to/your/script.js'; 
    script.type = 'text/javascript'; 
    var head = document.getElementsByTagName("head")[0]; 
    head.appendChild(script); 
} 
+0

太謝謝你了!很好的幫助 – Ronal 2009-09-03 20:47:12

+0

不客氣。 – seth 2009-09-03 20:57:33

+0

類型沒有必要,沒有區別(順便說一下) – 2009-12-19 04:30:04

-2

與AJAX獲取它,然後eval()函數的代碼。

+0

eval()有安全問題 – Evorlor 2015-04-16 14:38:24

11

@seth的答案是完全正確的,但你並不需要離開插入script元素的DOM,你可以刪除它,它加載剛過,也是你可能想知道的插入腳本就可以使用,例如,你可以:

function loadScript(url, completeCallback) { 
    var script = document.createElement('script'), done = false, 
     head = document.getElementsByTagName("head")[0]; 
    script.src = url; 
    script.onload = script.onreadystatechange = function(){ 
    if (!done && (!this.readyState || 
      this.readyState == "loaded" || this.readyState == "complete")) { 
     done = true; 
     completeCallback(); 

     // IE memory leak 
     script.onload = script.onreadystatechange = null; 
     head.removeChild(script); 
    } 
    }; 
    head.appendChild(script); 
} 

用法:

loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js", 
      function() { alert('jQuery has been loaded.'); }); 
相關問題