2014-05-13 8 views
2

현재 수정할 수없는 기존 웹 페이지에 삽입 할 수있는 JavaScript 애플리케이션을 개발하려고합니다. 응용 프로그램에는 특정 버전의 jQuery가 필요합니다. 응용 프로그램을로드하는 데 사용동적으로로드 된 JavaScript 애플리케이션에서 jQuery 충돌 방지

스크립트가하고있는 다음

// loading JavaScript needed by my application 
(function() { 
    document.write('<script src="../jquery-1.10.2.min.js"></script>'); 
    document.write(...); // load other scripts (using jQuery 1.10.2) 

    // storing the application's jQuery in a new namespace 
    // to avoid conflicts with other jQuery versions 
    document.write('<script type="text/javascript">' + 
     'appJQ = jQuery.noConflict(true);</script>'); // error: jQuery is undefined in IE<10 
})(); 

// initializing the application itself 
document.onload = function() { 
    // ... 
}; 

이 IE 9에서 IE < (10)를 제외하고, 내가 테스트 한 모든 브라우저에서 잘 작동하고 내가 오류를 얻고있다 절감이 jQuery는 정의되지 않았습니다.

document.onload 함수에서 새 네임 스페이스로 jQuery를 이동해도 다른 버전의 jQuery가 필요하면 내 응용 프로그램을 포함하는 웹 페이지의 다른 스크립트와 충돌이 발생합니다.

이 문제를 해결하는 방법에 대한 의견이 있으십니까? 도움 주셔서 감사합니다.

답변

1

대신 document.write를 사용하는 <script> 요소를 생성하고 해당 요소에 대한 onLoad 핸들러를 정의하려고 : 너희가 서로에 따라 여러 스크립트가있는 경우

(function() { 
    var script = document.createElement('script'); 
    script.src = '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js'; 
    script.onload = function() { 
     var appJQ = jQuery.noConflict(true); 
     // app initialization code 
    }; 
    var head = document.head || document.getElementsByTagName('head')[0]; 
    head.appendChild(script); 
})(); 

, 당신은 스크립트 로더를 사용하여 시도 할 수도 있습니다 HeadJS 또는 LABjs입니다.

더 많은 유연성을 통해 종속성을 관리하려는 경우 RequireJS, Browserify 또는 webpack과 같은 모듈 로더를 사용해 볼 수 있습니다.

+1

감사합니다. RequireJS를 사용하면 문제가 해결됩니다. –

0

document.write 호출은 문서가로드 된 것으로 간주 되어도 발생하며,이 경우 해당 함수의 내용 앞에 onload 함수가 실행될 수 있습니다. onload가 응용 프로그램 자체를 시작하도록보다 나은 방법으로 javascript 파일을로드하려고합니다. 함자의 대답에 따라

1

, 당신은 다른 방법으로에 로딩이 방법을 사용할 수 있습니다 :이 도움이

var s = document.createElement("script"); 
s.src = "../jquery.min.js"  // insert your own jQuery link 
s.onload = function() { 
    var appJS = jQuery.noConflict(true); 
} 

희망을.