JavaScript, Dom, and the browser

In working with the dom (document object model),  an issue is not addressed in the tutorials that I have been going through recently. Upon using one tutorial which has the external script referenced in the head of the web page, I was receiving an undefined error in the console of the developer tools. The script was not waiting for the web page to completely load or the dom tree to be finished, therefore the error. The fix for my external Javascript file?

  1. A much older fix is to add window.onload=()=> { the original javascript code } in the external javascript file . 
  1. Move the script element from the head section to the bottom of the document before the closing html tag of the web page.
  1. To leave the script element that references the external javascript file in the head section, but add a defer tag to the end of  the opening script tag . This is the preferred method today.

Each of these examples have the affect of making the script wait until the browser window is loaded. It resolved the undefined errors and now I am able to traverse and change elements and attributes using the dom with vanilla javascript. Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s