Tutorials JavaScript How to Add JavaScript
Ch 9 / 78
Chapter 2 Beginner 6 min read JavaScript

How to Add JavaScript to a Webpage

There are three ways to include JavaScript in your HTML — inline, internal, and external. Knowing when to use each one is a foundational skill every developer must have.

What you'll learn
Inline JavaScript via event attributes
Internal JS using the <script> tag
External JS with a separate .js file
Where to place <script> in your HTML
The defer and async attributes explained
Best practices for production projects

The Three Methods at a Glance

Every JavaScript instruction must be attached to an HTML page in one of three ways. Each has its own ideal use case — and its own drawbacks.

Method 01
Inline JS
JS written directly inside an HTML element's event attribute, such as onclick. Quick, but messy and hard to maintain.
⚠ Avoid in production
Method 02
Internal <script>
JS placed inside a <script></script> block within the HTML file. Good for small, page-specific logic.
✓ OK for single pages
Method 03
External .js File
JS lives in a separate .js file and is linked via the src attribute. The professional standard for all real projects.
✅ Best practice

Method 1 — Inline JavaScript

Inline JS is written directly inside an HTML tag using event attributes like onclick, onmouseover, or onchange. The browser runs the JS snippet the moment that event fires.

HTML — Inline JS
<!-- JS runs when the button is clicked -->
<button onclick="alert('Hello from inline JS!')">
  Click me
</button>

<!-- Inline with multiple statements -->
<button onclick="this.style.background='gold'; this.textContent='Clicked!'">
  Style me
</button>
Why to Avoid It
Inline JS mixes structure (HTML) with behaviour (JS) — violating separation of concerns. It's hard to debug, impossible to reuse, and can't be cached by the browser. Use it only for tiny demos or quick prototypes.

Method 2 — Internal <script> Tag

You can write JS inside a <script> block anywhere in your HTML document. The browser executes the script when it reaches that tag during parsing.

HTML — Internal Script
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Internal JS Demo</title>
</head>
<body>

  <h1 id="heading">Hello, World!</h1>
  <button id="btn">Change Heading</button>

  <!-- ✅ Script placed just before closing body tag -->
  <script>
    const btn = document.getElementById('btn');
    const h1  = document.getElementById('heading');

    btn.addEventListener('click', () => {
      h1.textContent = 'JavaScript changed me! ⚡';
      h1.style.color = '#f7df1e';
    });
  </script>

</body>
</html>
Note
Notice we use addEventListener rather than an onclick attribute — this is the clean, preferred way to attach events even when writing internal scripts.

Method 3 — External JavaScript File

The professional standard. All JS lives in one or more .js files that are linked to the HTML via a <script src="..."> tag. This approach separates concerns cleanly and lets the browser cache the JS file — so repeat visitors load your page faster.

Reusable
One app.js file can be linked by every page on your site — change it once, update everywhere.
Cacheable
Browsers cache external JS files. On repeat visits the file loads from disk — dramatically faster than re-downloading.
Clean HTML
Your HTML stays readable. No walls of script buried in the middle of your markup.
Tooling-friendly
Bundlers (Vite, Webpack), linters (ESLint), and formatters (Prettier) all work on .js files — not inline HTML.
index.html — linking external file
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Website</title>
  <!-- Link external CSS -->
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <h1>My Website</h1>

  <!-- ✅ Link external JS just before closing body -->
  <script src="app.js"></script>

</body>
</html>
app.js — your external script file
// app.js — no <script> tags needed here!

document.addEventListener('DOMContentLoaded', () => {
  console.log('app.js loaded and DOM is ready 🚀');

  const heading = document.querySelector('h1');
  if (heading) {
    heading.style.color = '#f7df1e';
  }
});
Pro Tip
You can link multiple external scripts on the same page. They execute in the order they appear. For large projects, use ES Modules (type="module") or a bundler like Vite to manage dependencies properly.
⚡
Free Resource
Download our JavaScript Project Starter Kit
HTML + CSS + JS boilerplate with best-practice folder structure.
Get Kit

Where to Place the <script> Tag

The position of your <script> tag in the HTML file matters because the browser parses HTML from top to bottom. If a script runs before the elements it targets exist in the DOM, it will fail.

<html>
<head>
<title>My Page</title>
<script src="app.js"></script> ← ❌ Too early — DOM not ready yet
</head>
<body>
<h1>Hello</h1>
<p>Some content...</p>
<script src="app.js"></script> ← ✅ Just before </body> — DOM is ready
</body>
</html>

Placing scripts at the bottom means all HTML elements are parsed and available before the JS runs. This avoids the classic Cannot read properties of null error that beginners hit when targeting elements that don't exist yet.

defer and async Attributes

If you must place a <script> in the <head> (common with third-party libraries), the defer and async attributes control when the script downloads and executes relative to HTML parsing.

normal
Default (blocking)
HTML parsing pauses, JS downloads and executes immediately. Page appears blank until the script finishes. Avoid for render-critical pages.
defer
Deferred execution
Script downloads in the background while HTML keeps parsing. Executes after the DOM is fully built, in document order. Best for most app scripts.
async
Async execution
Script downloads in the background and executes as soon as it's ready — may interrupt HTML parsing. Best for independent analytics or ad scripts.
Normal
HTML Parse
⏸ Pause
⬇ Download
▶ Exec
HTML Content.
defer
HTML Parse (uninterrupted)
▶ Exec
async
HTML Parse
⏸ Pause
▶ Exec
HTML Cont.
HTML — defer & async usage
<!-- ✅ defer — runs after DOM is ready, in order -->
<script src="app.js" defer></script>

<!-- async — runs as soon as downloaded, no order guaranteed -->
<script src="analytics.js" async></script>

<!-- ES Module — always deferred by default -->
<script type="module" src="main.js"></script>
Advertisement

Best Practices — Do's & Don'ts

Follow these rules on every project you build:

  • ✓ Use external .js files for all projects beyond a single HTML demo — keeps code organised and cacheable.
  • ✓ Add defer to <head> scripts — gets the performance benefit of early download while ensuring the DOM is ready before execution.
  • ✓ Use addEventListener instead of inline onclick="" attributes — separates behaviour from markup.
  • ✓ Use type="module" for ES6+ module-based projects — modules are always deferred and have their own scope by default.
  • ✗ Don't use inline event attributes (onclick="...") in professional code — difficult to test, impossible to maintain at scale.
  • ✗ Don't place a blocking <script> in <head> without defer/async — it will freeze rendering until the file downloads and executes.
  • ✗ Don't mix multiple methods in one project — pick external files and stick with them for maintainability.

Try It Yourself

This demo shows all three methods in action. Notice how the button uses addEventListener (not inline JS) and how the script tag sits at the bottom of the body.

Live Editor
✎ Editor
👁 Preview
Quick Check — Chapter 2

Which script attribute downloads the file in the background and executes it after the DOM is fully parsed, preserving document order?

Chapter Summary
  • There are 3 ways to add JS — inline attributes, internal <script> block, and external .js file.
  • External files are the professional standard — reusable, cacheable, and maintainable.
  • Place <script> just before </body> so the DOM exists when the script runs.
  • defer — downloads in background, executes after DOM is ready, preserves order. Best for app scripts in <head>.
  • async — downloads in background, executes immediately when ready, no order guaranteed. Best for analytics.
  • Always use addEventListener instead of inline onclick attributes in real projects.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel