2014-02-15 20 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" 
    }; 

雖然記錄是行不通的,並且 「沒有定義」 郎我試過很多東西儘管我嘗試過的任何事情都會變得很短暫

繼承人fiddle給例子,我用jQuery的CDN用於測試目的

+0

由於您錯過了括號,因此您的縮進被搞砸了。 – elclanrs

+0

我修復了缺失的圓括號 – EasyBB

回答

1

console.log(lang);語句執行加載lanugage文件之前,這個問題是關於異步代碼的概念。

加載語言文件後,您將不得不訪問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