2009-09-03 7 views
5

함수에서 외부 자바 스크립트를 내 문서에로드하는 방법을 알고 싶습니다.함수 호출시 외부 자바로드하기

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); 
} 

답변

14

이 하나의 방법입니다.

+0

너무 감사합니다! 중대한 도움 – Ronal

+0

당신을 진심으로 환영합니다. – seth

+0

유형이 필요하지 않습니다. (차이가 있습니다) –

-2

는 AJAX로 가져 오기 다음 평가() 코드 :

+0

eval()에 보안 문제가 있습니다. – Evorlor

11

@seth의 대답은 완전히 옳다,하지만 당신은 당신이로드 된 직후에 제거 할 수 있습니다, 또한 당신이 을 알고 싶어 할 수는 DOM에 삽입 된 script 요소를 떠날 필요가 없습니다 삽입 된 스크립트는 당신이 할 수있는 예를 들어, 사용할 수 있습니다 :

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.'); }); 
관련 문제