<script> tag with a specified
src attribute to load a separate document, put our code into the
<script> tag directly, or even add code to attributes of an HTML element. Let’s look at each option.
Script Tag with Source
We can add a
<script> tag with a
<link> element for CSS:
<!DOCTYPE html> <html> <head> <title>JS Example</title> </head> <body> <script src="example.js"></script> </body> </html>
A couple of important differences though. First, the
<script> element is not a void tag, so we a closing
</script>. Also, while traditionally we would also place
<script> elements in the
<head>, current best practice is to place them as the last children of the
Script Tag with Content
The reason the
<style> element for CSS. Typically we would also place this tag at the end of the body:
<!DOCTYPE html> <html> <head> <title>JS Example</title> </head> <body> <script> console.log(1 + 3); </script> </body> </html>
Why at the End of the Body?
The reason for placing
A good trick is to place any code that should not be run until all the web pages’ assets have been downloaded within the body of an event handler tied to the
'load' event, i.e.
As an Attribute
<button onclick="console.log(1+3)">click me</button>
This once-common strategy has fallen out of favor as it does not provide for good separation of concerns, and can be difficult to maintain in large HTML files. Also, only one event handler can be set using this approach; we’ll see an alternative method, Element.addEventListener() in the next section that is more powerful.
However, component-based development approaches like React’s JSX make this approach more sensible, so it has seen some resurgence in interest.
There is one aspect you need to be aware of though. Before you reference code artifacts like functions and variables, they must have been loaded in the interpreter. If you are using external files, these have to be retrieved by the browser as a separate request, and even though they may be declared in order in your HTML, they may be received out of order, and they will be interpreted in the order they are received
There are a couple of strategies that can help here. First, you can use the window’s