title: How to attach multiple js modules onto single firebase instance
body: <p>I am refactoring some code so that different javascript modules in different js files can use the same Firebase instance.  I also want to eliminate the possibility of race conditions as different modules are loaded.</p>
  
  <p>I believe that these are the steps that I would need to follow in order to avoid a race condition:</p>
  
  <ol>
  <li>Load firebase.js</li>
  <li>Initialize firebase prototype with authentication</li>
  <li>Execute external JS files module1.js and module2.js</li>
  </ol>
  
  <p>In code this will roughly translate to the following:</p>
  
  <pre><code>&lt;script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"&gt;&lt;/script&gt;
  &lt;script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
    if (firebase.apps.length === 0) {
      firebase.initializeApp({
        apiKey: "&lt;REMOVED&gt;",
        authDomain: "&lt;REMOVED&gt;",
        databaseURL: "&lt;REMOVED&gt;",
        storageBucket: "&lt;REMOVED&gt;",
        messagingSenderId: "&lt;REMOVED&gt;"
      });
    }
    firebase.auth().signOut().then(function () { 
       var customTokenUrl = "&lt;REMOVED&gt;";
       $.ajax({
         url: customTokenUrl,
         data: {},
         xhrFields: {withCredentials: true},
         crossDomain: true,
         success: function (token) {
           firebase.auth().signInWithCustomToken(token);
         },
         type: 'POST'
       });
    });
  &lt;/script&gt;
  &lt;script src="someurl/module1.js"&gt;&lt;/script&gt;
  &lt;script src="someurl/module2.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>This is roughly the code for both module1.js and module2.js:</p>
  
  <pre><code>var module1 = (function (MODULE) {
      ...
      ...
    firebase.auth().onAuthStateChanged(MODULE.onAuthStateChanged.bind(MODULE));
    function onAuthStateChanged(user) {
      if (user) {
        // User is signed in.
        MODULE.uid = user.uid;
        setWatchers(); // This is where I set the firebase refs
      } 
    }
    return MODULE;
  }
  </code></pre>
  
  <p>Here are the questions I have:</p>
  
  <ol>
  <li>In module1.js, is there a possibility that <code>onAuthStateChanged</code> won't fire?  I think that, theoretically, module1.js can execute after the auth state changed in firebase.  Wouldn't that make the <code>onAuthStateChanged</code> method not fire?</li>
  <li>Can the var <code>firebase</code> ever be undefined in module1.js?  </li>
  </ol>