JavaScript in the Browser: Getting Started
JavaScript is the language of the web browser. HTML gives a page structure, CSS gives it style and JavaScript makes it interactive: validating forms, fetching data without reloading, menus, games. It also runs on servers (Node.js), but this track focuses on the browser.
Adding JavaScript to a page
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello JS</title>
<script src="app.js" defer></script>
</head>
<body>
<button id="greet">Say hello</button>
</body>
</html>
defer downloads the script in parallel and runs it after the HTML is parsed, so your code can find elements. Prefer external files over inline <script> blocks: they are cacheable and work with a strict Content Security Policy.
app.js:
document.querySelector("#greet").addEventListener("click", () => {
alert("Hello from JavaScript!");
});
The developer console
Open DevTools (F12 or Ctrl+Shift+I / Cmd+Option+I) and choose Console. You can type JavaScript directly and see errors from the page.
console.log("value:", 42);
console.table([{ id: 1, name: "Ada" }, { id: 2, name: "Alan" }]);
console.error("something broke");
When a page "does nothing", the console almost always shows a red error with a file and line number. Read it first.
Strict mode and modules
Modern code uses ES modules, which are strict by default:
<script type="module" src="main.js"></script>
// main.js
import { formatPrice } from "./utils.js";
console.log(formatPrice(1999));
// utils.js
export function formatPrice(cents) {
return (cents / 100).toLocaleString("en-US", { style: "currency", currency: "USD" });
}
Modules have their own scope, so variables do not leak into the global namespace. They load as deferred scripts automatically.
Tools
- An editor: VS Code with ESLint and Prettier.
- A local server, because modules do not load from
file://URLs:python -m http.serveror the VS Code Live Server extension.
Exercise
Create a page with a button and a paragraph. Each click increases a counter shown in the paragraph. Log each click to the console.
Check yourself
- What does
deferdo? - Where do you look first when a page's JavaScript does nothing?
- Why do ES modules need a local web server?
Ваш прогресс сохраняется только в этом браузере.
Отправить на проверку (10 баллов)