What JavaScript Does in a Page
Everything you have built so far holds still. HTML says what each part of the page is and CSS says how it looks, but once the page has appeared, nothing on it changes until the visitor follows a link to another page. JavaScript is the language that changes a page while it is open: it answers a click, checks what someone typed, fetches new information and puts it on the screen. It is a real programming language, the first one in this book, and the one every browser runs.
Think of a stage play. HTML is the set: the walls, the doors, the table in the middle. CSS is the lighting and the costumes. JavaScript is the stagehands, who move things around while the audience watches. Stagehands can improvise, though, and a script cannot: it does exactly what is written, every time.
What Is JavaScript For?
JavaScript gives a page behaviour: what the page does in answer to something. A menu that opens when its button is pressed, a filter that hides the projects you are not interested in, a form that points at the empty field before anything is sent, a list that fills with fresh data from another site. Each of those is behaviour, and each is a chapter of this book.
Everything else already works without JavaScript, and it should keep working without it. A script can fail to download on a poor connection, a browser extension can block it, and one mistake in it can stop it running. When that happens, a page whose content lives in the HTML still shows its text, its links and its forms. So the rule from Chapter 1 holds: the page works as HTML first, and JavaScript makes it better.
Adding a Script, and What defer Does
JavaScript lives in its own file, the way CSS does. In your my-site folder, make a new folder called js, and inside it a file called main.js. The letters after the dot, js, tell the editor and the browser what kind of file it is.
The page loads that file with a script element in its head, directly below the stylesheet link. Its src attribute is the path to the file, the same kind of path a link uses. The block below shows the end of the head with the new line added. The script element needs its closing tag even though nothing goes between the two tags. Add the same line to projects.html and contact.html, so all three pages share one script. Nothing on the page changes yet, because the file is empty.
<head> <!-- the lines you already have --> <link rel="stylesheet" href="css/style.css"> <script src="js/main.js" defer></script> </head>
Topic 2 of Chapter 1 showed the browser reading the HTML from top to bottom. A plain script element interrupts that reading. The browser stops, downloads the script, runs it, and only then carries on with the rest of the page. The page appears later, and worse, the script runs before the elements below it exist. A script that looks for the list of projects finds nothing, because the browser has not read that far.
The defer attribute changes the order. The browser starts downloading the script at once, while it keeps reading the HTML, but it waits to run the script until the whole page has been read. By then every element exists, so the script can reach all of them. Several deferred scripts run in the order they appear in the page.
You will see older pages put their script elements at the very end of the body instead. That trick gets the same running order, but the browser finds the script only at the very end of the HTML, so on a long page its download starts later. A deferred script in the head is found in the first lines and can start downloading sooner, which is why this book uses it.
The Console: Where a Script Talks to You
The Console is the DevTools panel where you can type JavaScript and see the answer at once. It is also where scripts write their messages and where errors appear. Open DevTools as in Chapter 2 and choose the Console tab, or go straight there with Ctrl+Shift+J on Windows or Cmd+Option+J on macOS.
Click in the Console, type two plus two, and press Enter. The Console answers 4. Now type the tagline inside double quotes and press Enter: the Console gives the same text back. The quotes mark where a piece of text starts and ends, so JavaScript treats it as text rather than as instructions. In the blocks in this book, a line starting with a greater-than sign is what you type, and the line under it is the Console's answer. The Console shows text answers in single quotes; that is only how it displays text.
> 2 + 2 4 > "I build small, useful things for the web." 'I build small, useful things for the web.'
If you paste code into the Console, Chrome may refuse the first time and ask you to type the words allow pasting. That warning exists because scammers tell people to paste code they do not understand. Type the code yourself if you prefer; in this book you will always understand what you paste.
A script talks to the Console with console.log, which means "write this in the Console". Put one line in main.js, save it, and reload the page. The Console shows the words main.js loaded, and on the right, the file name and the line number the message came from. That one message proves the path is right and the script ran.
console.log("main.js loaded");
main.js loaded
If nothing appears, look for a red line instead. A mistyped path gives an error saying the file was not found, with the number 404, the code a server sends back for "not found". Fix the path in the script element and reload. Short experiments in the next topics go straight into the Console; longer ones go into main.js, and you clear them out again when you are done.
What Is a Program?
A program is a list of instructions the computer follows exactly, in order, from the top. Each instruction is called a statement, and in this book every statement ends with a semicolon, the way a sentence ends with a full stop. JavaScript can often guess where a missing semicolon belongs, but the guesses occasionally go wrong, so the book always writes them.
The word that matters is "exactly". The HTML parser forgives mistakes and guesses what you meant. JavaScript does not guess: a missing quote or bracket stops the script with an error. A mistake in a program is called a bug, and every bug lives in the gap between what you meant and what you wrote. Topic 5 shows how to read the errors that point at that gap.
JavaScript, Java and ECMAScript
Despite the name, JavaScript has nothing to do with Java, a different language for different jobs. The name was a marketing decision in 1995, when Java was fashionable. The official standard for the language is called ECMAScript. It is written by the committee Chapter 1 named, TC39, and a new edition comes out every year. When MDN mentions a version such as ES2015, it means the edition of that standard from that year.
If you have written Python, the ideas in the next two chapters will be familiar, but the punctuation will not: braces instead of indentation, and semicolons at the ends of lines.
- "JavaScript and Java are related." Only by name. They are separate languages, designed by different people, for different jobs.
- "A page needs JavaScript to show its content." It should not. Content written in the HTML shows up even when a script fails to load or stops with an error.
- "
console.logshows messages to visitors." Only someone with DevTools open ever sees them. Visitors see only what a script puts on the page itself.
- This is where you start programming, with instant feedback in a tool you already have open.
- Loading scripts with
deferprevents the most common "my script cannot find the element" bug before it ever happens.
Knowledge Check
What does the defer attribute on a script element change?
- The script downloads only after the page is shown
- The script runs after the whole page has been read
- The script runs only when a visitor clicks something
- The script runs before the browser reads the page
What is the Console in DevTools for?
- Showing messages to every visitor of the page
- Editing the HTML file and saving it to disk
- Typing JavaScript and reading a script's messages
- Listing the CSS rules that apply to an element
A page's script fails to download. What should still work?
- Nothing, because the script controls the page
- Only the parts that JavaScript created earlier
- Only the Console, which reports the failure
- The text, links and forms written in the HTML
Where does a message written with console.log appear?
- In the Console, for anyone with DevTools open
- On the page, below the last element in the body
- In a pop-up window that the visitor must close
- In a log file saved next to main.js in the js folder
You got correct