HTML and CSS Reference
In-Depth Information
<meta charset="utf-8">
<title>Inline Scripts</title>
</head>
<body>
<script>
window.onload = function() {
document.write('Hello World!');
};
</script>
</body>
</html>
5.
Save the file.
Now view this file in your web browser. You should see that
Hello World!
is displayed on the page. Let's dis-
sect this code a little.
JavaScript code will be executed only when you tell the browser to execute it. In this case, you want the code to run
as soon as the page has loaded, so you need to tell that to the browser. The first line of your code does this.
JavaScript uses objects to keep track of things like the browser window, document, and HTML elements. When a
page finishes loading, the
window
object triggers an event called
onload
. To execute code when the page loads,
you need to attach this code to the
onload
event. In the code in the preceding Step 4, you do this by assigning a
new function to the
window.onload
event using the
=
(equals sign) operator. All the code that you place within
this function will now be executed when the
onload
event triggers:
window.onload = function() {
document.write('Hello World!');
}
To ensure that things are working correctly, you included a line of code that will write the text
Hello World!
onto the screen. To do this, you grabbed the
document
object and used its built-in
write
function. The text that
you want to be displayed is placed within the parentheses of the
write
function. You learn more about JavaScript
functions later in this chapter.
That's it for inline scripts—pretty straightforward. As you can see, if you had a lot of HTML and JavaScript code in
one page, it could be a bit of a pain to maintain, not to mention the fact that if you want to use this code on more than
one page you would have to copy and paste it into each page. Then if you wanted to make a change, you would have
to make the update in numerous different files. Things can get messy very quickly. This is why it is often better to
put your JavaScript code into an external file.
Linking External JavaScript Files
Dedicated JavaScript files should use the
.js
file extension. Make sure that your text editor has syntax highlighting
for JavaScript, because this can help to catch any errors (or
bugs
) in your code.
As with external stylesheets, you need to link JavaScript files to your HTML files. You do this using the
<script>
element.
You can use the
src
attribute on the
<script>
element to specify an absolute or relative path to your JavaScript
file, in the same way that you do for images.