REAL O G
REAL O G

Reputation: 685

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?

Upvotes: 0

Views: 64

Answers (2)

Shadi Shaaban
Shadi Shaaban

Reputation: 1720

Use Immediate Invoking Function:

You could wrap your randomGreeting() in an immediate invoking function code block to get it executed as soon as it's declared and thus your code will work:

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

Upvotes: 0

Steve
Steve

Reputation: 2046

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>

Upvotes: 1

Related Questions