Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 122 Β· CSS and JavaScript in HTML

Adding JavaScript

Add JavaScript to HTML with inline and external script elements, choose where to place them, compare defer, async and type="module", and use noscript fallbacks.

HTML gives a page its structure and CSS gives it style. JavaScript gives it behavior: it reacts to clicks, checks forms before they are sent, loads new data without reloading the page and updates the content on the fly.

This lesson is about the HTML side of JavaScript: how to put scripts into a page with the <script> element, where to place them, and how the defer, async and type="module" attributes change when they run. You do not need to know JavaScript yet. The examples are short, and the following lessons on events and the DOM build on them.

Your first script

The <script> element holds JavaScript code. When the browser reaches it while reading the HTML, it runs the code:

A first script

Two things happened:

  1. The script found the paragraph by its id and replaced its text. That changed the page itself.
  2. console.log() wrote a message to the console, a developer-only log. In this editor the console output is shown under the preview; in a normal browser you see it in DevTools (press F12).

console.log() is the simplest way to check what your code is doing, and you will use it constantly.

type="text/javascript" is not needed. Old tutorials put it on every script. JavaScript is the default, so a plain <script> is all you need.

Inline vs external scripts

Like CSS, JavaScript can live inside the page or in a separate file.

Inline β€” code between the tags, as above. Fine for tiny, page-specific snippets.

External β€” the code lives in a .js file and the src attribute points to it:

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

Rules to remember:

  • A <script> with src must still have a closing </script> tag. <script src="app.js" /> does not work in HTML.
  • When src is present, any code between the tags is ignored. Use two separate elements if you need both.
  • The .js file contains only JavaScript β€” no <script> tags.

External scripts are the norm on real sites for the same reasons as external stylesheets: one file shared by every page, cached by the browser and kept apart from the content.

Placement and the blocking problem

A plain <script> is parser-blocking. When the browser meets one, it stops building the page, downloads the file (if it is external), runs it and only then carries on with the HTML.

That causes two classic problems when scripts sit in the <head>:

  1. Slow pages. Nothing below the script is displayed until it has downloaded and run.
  2. Missing elements. The script runs before the elements further down exist, so code that looks for them finds nothing.
A script that runs too early

The first script logs null: when it ran, the paragraph had not been parsed yet. The second script, placed after the paragraph, finds it.

The traditional fix was to put all scripts at the end of <body>. That still works, but modern HTML has a cleaner solution.

defer: the modern default

Add defer to an external script and put it in the <head>:

HTML
<head>
  <meta charset="utf-8">
  <title>Recipe Box</title>
  <script src="/js/app.js" defer></script>
</head>

A deferred script:

  • downloads in parallel while the browser keeps building the page,
  • runs after the whole document has been parsed, so every element exists,
  • runs in order with other deferred scripts, and before the DOMContentLoaded event.

You get early downloading and safe timing. For most scripts that touch the page, defer in the <head> is the best choice.

async: run as soon as it arrives

HTML
<script src="/js/analytics.js" async></script>

An async script also downloads in parallel, but it runs the moment it finishes downloading β€” possibly before the page is parsed, and in no guaranteed order relative to other async scripts. That suits independent scripts that do not depend on the page or on each other, such as analytics or a stand-alone widget.

Attribute Downloads Runs Order kept?
(none) Blocks parsing Immediately Yes
defer In parallel After parsing finishes Yes
async In parallel As soon as downloaded No

defer and async only work on external scripts (with src). On inline classic scripts they are ignored.

You can see the difference in the editor by using data: URLs, which put a tiny script file directly in the src:

defer in action

The deferred script appears first in the code but logs last, because it waits until the whole document has been parsed. (data: URLs are only a trick for this demo; real sites use files.)

type="module": modern JavaScript modules

Modern JavaScript is organized into modules β€” files that import code from other files and export their own:

HTML
<script type="module" src="/js/main.js"></script>
JavaScript
// main.js
import { formatPrice } from "./utils.js";

console.log(formatPrice(12.5));

Module scripts behave differently from classic scripts:

  • They are deferred automatically, even inline ones. No defer attribute needed. (You can add async to run a module as soon as it is ready.)
  • They run in strict mode, which turns some silent mistakes into errors.
  • Variables declared at the top level stay inside the module instead of becoming globals.
  • External modules are loaded with CORS rules, so opening the HTML file directly from your disk (file://) often fails. Use a local web server.
An inline module

The script comes before the button in the code, yet it finds it β€” because modules are deferred.

noscript: when scripts do not run

Some visitors browse with JavaScript turned off, a script can fail to load, or a corporate network can block it. The <noscript> element shows fallback content in exactly that case:

HTML
<noscript>
  <p>The interactive map needs JavaScript. You can still
    <a href="/directions.html">read the written directions</a>.</p>
</noscript>

When scripting is enabled, browsers skip its content entirely, so you will not see it in the editor. Better still is progressive enhancement: build the page so its core content and links work without JavaScript, then let scripts add extra features on top.

Good habits

  • Prefer external files with defer (or type="module") in the <head>.
  • Keep inline scripts small. Sites with a strict Content Security Policy may block them completely.
  • Never paste in scripts from sources you do not trust: a script can read and change everything on your page.
  • Watch the console. Errors appear there, and one uncaught error stops the rest of that script.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Which is the correct way to load an external script?

    Scripts use src, and the element always needs a closing </script> tag in HTML.
  2. 2. A plain script in the <head> tries to change a paragraph further down the page, but gets null. Why?

    A classic script runs as soon as the parser reaches it. Elements below it do not exist yet. Use defer, a module or move the script down.
  3. 3. Which attribute downloads a script in parallel and runs it after the document is parsed, keeping the order of scripts?

    defer keeps order and waits for parsing. async runs as soon as the file arrives, in any order. lazy is not a script attribute.
  4. 4. What is true about <script type="module">?

    Module scripts, inline or external, are deferred automatically and always use strict mode.

Summary

  • <script> adds JavaScript, either inline or from an external file with src (always close the tag).
  • A plain script blocks parsing and can only see elements above it.
  • defer downloads in parallel and runs in order after parsing β€” the best default for page scripts.
  • async runs as soon as the file arrives, in no fixed order; use it for independent scripts.
  • type="module" enables import/export and is deferred automatically; <noscript> shows fallbacks.

Next lesson: Event Attributes and Event Listeners β€” making pages respond to clicks, typing and more.