1

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

2
  • Your indentation got messed up because you missed a parentheses. Commented Feb 15, 2014 at 6:08
  • I fixed that missing parentheses Commented Feb 15, 2014 at 6:12

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

ahh great it works perfectly now. asynchronousity always makes me flop over dead trying to figure that out haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.