javascript - Includes
Hey there, junior coder! Today, we're going to learn about why the place where you put your JavaScript code in your HTML file is super important. We'll explore the difference between putting it at the top of your document versus the bottom.
Imagine you're building a house. You need to have the walls up before you can paint them, right? Similarly, in web pages, the HTML elements need to load before your JavaScript can interact with them.
Example 1: JavaScript at the Top
Here's an example where we put our JavaScript code at the top of our HTML file:
What's happening here?
- We have a script at the top, inside the
<head>
tag. - The script tries to find a paragraph with id
myParagraph
and change its text. - But the paragraph is defined after the script, in the
<body>
tag. - This means that when the script runs, the paragraph doesn't exist yet!
- As a result, JavaScript can't find the element and the code doesn't work as expected.
Example 2: JavaScript at the Bottom
Now let's see what happens when we put our JavaScript code at the bottom of our HTML file:
What's happening here?
- We moved the script to the bottom, just before the closing
</body>
tag. - Now, when the script runs, the paragraph with id
myParagraph
has already been loaded. - JavaScript can find the element and change its text successfully!
Example 3: Using window.onload
You can also keep your script at the top and make sure it runs after the page loads by using window.onload
:
What's happening here?
- We kept the script at the top, but we wrapped our code inside the
window.onload
function. - This tells the browser to wait until the whole page has loaded before running the code.
- Now, even though the script is at the top, it works correctly because it waits for the page to load.
Tips to Remember:
- Place Scripts at the Bottom: Putting your JavaScript code just before the closing
</body>
tag ensures all HTML elements are loaded before the script runs. - Use
window.onload
orDOMContentLoaded
: If your script is in the<head>
, wrap your code in these events to make sure it runs after the page loads. - Faster Page Load: Placing scripts at the bottom can make your web pages load faster for the user.
Practice Time!
Try moving the script tag in the following code and see what happens:
If you move the script to the head, the code might not work because the element with id greeting
doesn't exist yet when the script runs. Try using window.onload
to fix this.