Lesson 23 +10 XP

Scripting in HTML

JavaScript makes pages do things. HTML's job is to include the JavaScript.

script: adding JavaScript

Put JavaScript inside <script>:

Code

html
<script>
  alert("Hello!");
</script>

Or link to a separate file with src:

Code

html
<script src="app.js"></script>

Where to put it

A common pattern: put &lt;script&gt; right before &lt;/body&gt; so the page content loads first.

Code

html
<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.
Code

html
<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=&quot;module&quot;: a JavaScript module (can use import/export).
  • type=&quot;importmap&quot;: tells the browser where to find modules.
  • type=&quot;speculationrules&quot;: gives the browser rules about pages to preload.
Code

html
<script type="module" src="app.js"></script>

noscript

&lt;noscript&gt; shows content ONLY when JavaScript is turned off.

Code

html
<noscript>
  <p>Please enable JavaScript to use this site.</p>
</noscript>

canvas: a drawing board

&lt;canvas&gt; is a blank drawing area that JavaScript can paint on. It needs width and height.

Code

html
<canvas id="game" width="300" height="150"></canvas>

The drawing happens with JavaScript:

Code

js
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 50);

TL;DR

  • &lt;script&gt; adds JavaScript (inline or via src).
  • Put scripts before &lt;/body&gt;, or use defer/async.
  • &lt;noscript&gt; shows fallback content without JavaScript.
  • &lt;canvas&gt; is a drawing board for JavaScript.