Search code examples
javascriptfunctionvariablesexternal

Javascript variable between two external files


I'm new to JS, and I don't understand why this doesn't work. The following is in a file called test1.js

var greeting;

function randomGreeting(){
    var greet = new Array("BORING JS TEST ALERT", "EXCITING JS TEST ALERT", "AWESOME JS TEST ALERT");
    var randGreet = Math.floor(Math.random() * greet.length);

    greeting = {
        alert: greet[randGreet]
    };
}

In a separate test2.js file:

alert(greeting.alert);

In my HTML I have randomGreeting() being called in the body's onLoad, and I have test1.js loaded before test2.js, but I still get undefined from the console when test2 is ran. Why?


Solution

  • you have a race condition against test2.js running and the document onload event which fires much later.

    You either delay the alert until the variable is set

    (function(){
       if (typeof greeting == "undefined")
          return window.setTimeout(arguments.callee, 10);
    
       alert(greeting.alert);
    }());
    

    if you're not recalling randomGreeting, you can just inline it

    var greet = new Array("BORING JS TEST ALERT", "EXCITING JS TEST ALERT", "AWESOME JS TEST ALERT");
    var randGreet = Math.floor(Math.random() * greet.length);
    var greeting = {
        alert: greet[randGreet]
    };
    

    Or you can change the scripts to use the defer attribute

    <script scr="test1.js"></script>
    <script scr="test2.js" defer></script>
    <script>
    window.onload = function(){
        alert(greeting.alert);
    };
    </script>