I'm trying to working with an IIFE and a language file to make my code localized. Problem is that the IIFE keeps saying that the variables inside the language code don't exist. I'm trying to figure out why, if someone could explain to me a bit why and how I should go about it this would be awesome!

Example

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');

Language Code-

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

Though logging just does not work and lang is "not defined" I've tried plenty of things to get this to work though anything I've tried is coming up short.

heres a fiddle to give example and I used jQuery CDN for testing purposes

有帮助吗?

解决方案

This console.log(lang); statement is executed before the lanugage file is loaded, the problem is about concept of asynchronous code.

You will have to access the lang object after language file is loaded.

Here is how you can fix this.

(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');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top