Order of execution (Asynchronous)?

Asked

Viewed 29 times

-3

function populate () {
    for (var i = 0; i < 4; i++) {
        guess('btn' + i);
    }
}

function guess(id) {
    var button = document.getElementById(id);
    button.onclick = function() {
        console.log(button.innerHTML);
    }
}

populate();

How does the execution order of this code work? And why do I have to put mine in the body to work, and not in the head?

1 answer

1


There is nothing asynchronous in this code, you must be getting confused with the order in which the files are loaded in your browser (which is an asynchronous process).

And because I have to put mine in my body to work, and not in head?

It depends on how you are including the script in the HTML. If you are including way inline (writing the script in the same file), the script will be executed immediately. This means that the getElementById will only be able to fetch elements that have already been loaded, so these elements need to be declared before the script.

If the script is declared in another file, in the style

<script src="meuscript.js"></script>

This means that it will be loaded on a different request, asynchronously. This means that until it is loaded, it is possible that all of your HTML is already loaded/processed, and so, even if the script is stated in the head, it is likely (but not guaranteed) that he can read elements of the body with the getElementById.

For these cases you need to use attributes in the script element, or in Javascript, so that the code is only executed after the HTML is already loaded.

  • I searched now based on your response and found DEFER, and it really worked, but it is recommended to use DEFER or put the script in the same body ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.