2014-02-15 2 views
1

IIFE와 언어 파일을 사용하여 코드를 현지화하려고합니다. 문제는 IIFE가 언어 코드 내의 변수가 존재하지 않는다고 계속 말하고 있다는 것입니다. 나는 왜 누군가가 나에게 설명 할 수있는 이유를 알아 내려고 노력하고 있는데, 왜 내가 어떻게해야하는지에 관해서는 이것이 대단하다!JavaScript IIFE가 외부 로컬 리 제이션/lang 코드와 함께 작동

단지 작동하지 않고 랭이 "정의되지"로깅이 내가 일을 많이 해봤지만 예

IIFE-

(function(w,d,id){ 
    if(!d.getElementById(id)){ 
     var fjs = d.createElement('script'); 
      fjs.id=id; 
      fjs.src="url_lang_file";//this is where the language code is inserted 
      document.head.appendChild(fjs); 
     } 

    console.log(lang); 
    })(window,document,'support_lang'); 

언어 코드 -

var lang={ 
     hello:"hello", 
     bye:"GoodBye" 
    }; 

내가 시도한 어떤 것도 짧게 나오고 있지만 이것이 작동하도록하기 위해서.

을 heres fiddle 예를 제공하고 I는 테스트 목적으로이 console.log(lang); 문이 lanugage 파일을로드하기 전에 문제가 비동기 코드의 개념에 관한 실행

+0

괄호를 놓쳤으므로 들여 쓰기가 엉망입니다. – elclanrs

+0

누락 된 괄호를 수정했습니다. – EasyBB

답변

1

에 대한 jQuery를 CDN을 사용했다.

언어 파일을로드 한 후 lang 개체에 액세스해야합니다.

다음은이 문제를 해결할 수있는 방법입니다.

(function(win,d,id){ 
    if(!d.getElementById(id)){ 
     var fjs = d.createElement('script'); 
      fjs.id=id; 
      fjs.src="lang.js";//this is where the language code is inserted 
      document.head.appendChild(fjs); 
      fjs.onload = function(){ 
      //console.log(lang); 
      //here your lang object is accessable after load file. 
      } 
      //console.log(lang); 
      //here lang object is not accessible 
      //because it executes before the language file is loaded 

     } 
    })(window,document,'support_lang'); 
+0

이제 완벽하게 작동합니다. 비 동시성은 항상 내가 하하를 알아 내려고 죽은자를 때려 눕히게 만듭니다. – EasyBB