With CSS, you learned that styles could be defined in three ways: in an internal stylesheet using the style
tag, in an external stylesheet that is included with a link
tag, or in an element's style
attribute. External stylesheets are preferred because they can be reused across pages and keep the concerns of structure and presentation separate.
Similarly, JavaScript code be written in several places. One option is to write it internally in a script
tag inside the head
element:
Open your browser's developer console to see the output from console.log
.
Another and more reusable option is to write the JavaScript in a separate file and include it using the script
tag with a src
attribute:
The script element must have a closing tag, even when empty. To include multiple scripts, you add multiple script elements. Why a script isn't included using a link
tag, as is done with an external stylesheet, is a mystery.
As soon as the browser encounters a script element, it executes its code. If your script appears in the head element but is intended to manipulate elements that appear in the body, this early execution will fail. For this reason, you will often need to place the script element after the referenced elements and usually as the last child of the body element:
Read on to learn about what getElementById
and innerText
mean.