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

使用外部本地化/lang代码的JavaScript IIFE,javascript,function,localization,lang,iife,Javascript,Function,Localization,Lang,Iife,我正在尝试使用IIFE和语言文件使代码本地化。问题是IIFE一直说语言代码中的变量不存在。我想弄明白为什么,如果有人能给我解释一下为什么,我该怎么做,那就太棒了 示例 生活- 语言代码- var lang={ hello:"hello", bye:"GoodBye" }; 虽然日志记录不起作用,而且lang是“未定义的”,但我已经尝试了很多方法来实现它,尽管我尝试过的任何方法都有不足之处 下面是一个示例,我使用jQuery CDN进行测试这个控制台.lo

我正在尝试使用IIFE和语言文件使代码本地化。问题是IIFE一直说语言代码中的变量不存在。我想弄明白为什么,如果有人能给我解释一下为什么,我该怎么做,那就太棒了

示例

生活-

语言代码-

   var lang={
       hello:"hello",
       bye:"GoodBye"
   };
虽然日志记录不起作用,而且lang是“未定义的”,但我已经尝试了很多方法来实现它,尽管我尝试过的任何方法都有不足之处

下面是一个示例,我使用jQuery CDN进行测试

这个
控制台.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');

你的缩进搞糟了,因为你漏掉了一个括号。我修复了那个漏掉的括号。太好了,现在它工作得很好。异步性总是让我在试图弄明白这一点时晕头转向,哈哈。
(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');