JavaScript IIFE使用外部本地化/ lang代码

时间:2014-02-15 06:05:46

标签: javascript function localization lang iife

我正在尝试使用IIFE和语言文件来使我的代码本地化。问题是IIFE一直说语言代码中的变量不存在。我想弄明白为什么,如果有人能向我解释一下为什么以及我应该如何解决这个问题会很棒!

示例

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

虽然日志记录不起作用且lang“未定义”但我已经尝试了很多东西来实现这一点,尽管我尝试过的任何东西都很短暂。

继承人fiddle示例,我使用jQuery CDN进行测试

1 个答案:

答案 0 :(得分:1)

这个console.log(lang);语句在加载语言文件之前执行,问题在于异步代码的概念。

加载语言文件后,您必须访问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');
相关问题