2012-09-26 3 views
1

자바 스크립트 코드 document.write 메서드를 사용하여 다른 서버의 자바 스크립트 파일을 내 웹 페이지로로드하려고합니다. 같은jQuery의 서버에서 파일을 찾는 방법은 무엇입니까?

document.write("<script type='text/javascript' src='http://www.mydomain.com/js/myscript.js'></script>"); 

는하지만 각각의 경로는 브라우저 오류 콘솔에서의 던져 404 File not found error 있도록 myscript.js을 가지고하지 않습니다.

어떻게 이런 종류의 오류를 예측하고 피할 수 있습니까?

가능한 경우 오류를 예측하기 위해 놓친 js 파일 기능을 호출하는 대신 대체 메시지를 표시합니다.

+0

경우 - 당신은 스크립트를로드하는 페이지에서이 있는지 확인합니다. 예를 들어, myscript.js가 "g"를 전역 변수로 정의하는 경우 "if (g == undefined) some error throw"를 확인하십시오. –

답변

2

를 사용하여 자바 스크립트를로드 할 스크립트를 요청한 파일 (이 질문에서 보인다) 그냥 자원의 (HEAD 방법) 이전 아약스 전화를하고 있는지 확인하여 도메인에

function onReadyState() { 
    console.error("Unable to load file: "+ this.src + ". Please check the file name and parh."); 
    return false; 
} 

function addJS(path){ 
    var e = document.createElement("script"); 
    e.onerror = onReadyState; 
    e.src = path; 
    e.type = "text/javascript"; 
    document.getElementsByTagName('head')[0].appendChild(e); 
} 

addJS('http://www.mydomain.com/js/myscript.js'); 
+0

감사합니다. 샘플 [http://jsbin.com/ovexip/1/]을 테스트했습니다. 편집하다) – sureshunivers

0

경우 응답 상태는 200 (확인) 또는 304 (수정되지 않음)

0

더 DETA이 접근

var js="ajax/test.js"; 

    $.getScript(js) .done(function(script, textStatus) { 
      var script = document.createElement('script'); 
      script.type = 'text/javascript'; 
      script.src = js; 
      document.body.appendChild(script);; 
    }) 

을 시도하다 ILS : jQuery.getScript

는 참고 : 스크립트 객체 또는 글로벌 변수의 어떤 종류를 생성 Use javascript (not jQuery) to manipulate HTML DOM

관련 문제