简体   繁体   中英

why does assigning a variable to 'textContent' element have to be at bottom of page?

I am practicing some concepts in Javascript and ran across something while trying to re-create my own code. I am getting a 'ReferenceError: responseH1 is not defined' if assigning my h1.textContent to a variable name above my code which makes sense to me.

My expectation is that assigning the variable above the code would be the normal course of action before using variables, however, I get the 'ReferenceError' unless I put it at the bottom of my code. I googled why this is but could not turn anything up. I don't even know what to search for to find a solution.

let section = document.querySelector('body');
section.innerHTML = '';
let h1 = document.createElement('h1');
section.appendChild(h1);
// h1.textContent = responseH1; /// This creates an Error if on top. Why is this?

let machineOn = true;

let score = '15';

if (machineOn = true) {
    responseH1 = 'Welcome! Your Machine is turned on!';
} else {
    responseH1 = 'Hello, Your Machien is turned off!';
}

h1.textContent = responseH1; // This makes it work when on bottom. Why is this?

Because the browser parses the DOM - which, before parsing, is just a string - top-down , element by element.

If on the way it finds Javascript, it runs the code immediately.

Should the element in question be below the Javascript, then the element isn't parsed yet, and thus, doesn not yet exist in the document object model (DOM).

To help with these kind of issues, the browser has an event which tells you when the DOM is fully parsed, that you can register your code as a listener on, which means your code is executed as soon as the event occurs. The event is called DOMContentLoaded . If you use that, the position of your JS in your HTML no longer matters.

Example:

document.addEventListener('DOMContentLoaded', function(event) {
  // your code here
});

You also have another option, if your Javascript code is in an external file.

You can include the script in the <head> section of your document, and add the defer attribute.

<script src="./path/to/my-script.js" defer></script>

This does two things:

  1. Delay execution of the code in the script until DOMContentLoaded has occurred.
  2. Delay the end of DOMContentLoaded until your script is fully executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM