0

If one.js happens to finish loading before two.js even gets parsed, will x exist? Surely this is possible because once an asynchronous script has been loaded, it's immediately executed and blocks further parsing of the HTML file. Thereby blocking two.js before it defines x.

To my knowledge, JavaScript doesn't need to resolve variables within a function. Instead, it waits until the function is executed to determine it's existence. Since x.prt isn't used until the window and it's resources (including two.js) have loaded, it should be safe load both scripts asynchronously, right?

jsfiles.html:

...
<script src="lib/one.js" type="text/javascript" async="async"></script>
<script src="lib/two.js" type="text/javascript" async="async"></script>
...

one.js:

window.addEventListener("load", function() {
    x.prt("Will this print 100% of the time?");
}, false);

two.js

var x = {
    prt: function(str) {
        console.log(str + " Or will this definition not be seen?");
    }
};
2
  • Have you tried running the code in a web browser? Commented Jul 28, 2015 at 21:45
  • It works. But I'm not sure if my reasoning is correct. Commented Jul 28, 2015 at 21:48

1 Answer 1

1

JavaScript doesn't attempt to evaluate anything inside a function until the function executes. It will not attempt to look up x until the function executes, at which point x will exist as a global variable.

If one.js happens to finish loading before two.js even gets parsed, will x exist?

No, but it doesn't matter, because you don't need x to exist to define a function which uses x. x will exist by the time your window's load callback fires and your callback tries to use x.

Sign up to request clarification or add additional context in comments.

1 Comment

As a side question... Is there a benefit to using the var keyword in the global scope?

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.