Loading lessons...
Scripting in HTML
Scripting in HTML
JavaScript makes pages do things. HTML's job is to include the JavaScript.
script: adding JavaScript
Put JavaScript inside <script>:
<script>
alert("Hello!");
</script>
Or link to a separate file with src:
<script src="app.js"></script>
Where to put it
A common pattern: put <script> right before </body> so the page content loads first.
<body>
... content ...
<script src="app.js"></script>
</body>
defer and async
defer: download the script while the page reads, then run it after. Scripts run in order.async: download and run whenever it's ready. Fast, but scripts may not run in order.
<script src="app.js" defer></script>
<script src="other.js" async></script>
script type
The type of a script says what kind of script it is:
- (no type): a normal JavaScript script.
type="module": a JavaScript module (can use import/export).type="importmap": tells the browser where to find modules.type="speculationrules": gives the browser rules about pages to preload.
<script type="module" src="app.js"></script>
noscript
<noscript> shows content ONLY when JavaScript is turned off.
<noscript>
<p>Please enable JavaScript to use this site.</p>
</noscript>
canvas: a drawing board
<canvas> is a blank drawing area that JavaScript can paint on. It needs width and height.
<canvas id="game" width="300" height="150"></canvas>
The drawing happens with JavaScript:
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 50);
TL;DR
<script>adds JavaScript (inline or viasrc).- Put scripts before
</body>, or usedefer/async. <noscript>shows fallback content without JavaScript.<canvas>is a drawing board for JavaScript.