Web Analytics

Adding JavaScript to HTML

Beginner ~7 min read

The <script> Tag

JavaScript code is added to HTML using the <script> tag. There are three main ways to include JavaScript in your web pages.

Method 1: Inline JavaScript

Write JavaScript directly inside the <script> tag. This is great for small scripts and learning.

HTML
CSS
JS

Method 2: Internal JavaScript

Place JavaScript in the <head> or <body> section. Common for page-specific scripts.

HTML
CSS
JS

Method 3: External JavaScript

Link to an external .js file using the src attribute. Best for larger projects and code reusability.

HTML File

<!DOCTYPE html>
<html>
<head>
  <title>External JavaScript</title>
</head>
<body>
  <h1>My Page</h1>
  
  <!-- Link to external JavaScript file -->
  <script src="script.js"></script>
</body>
</html>

script.js File

// External JavaScript file
console.log('External script loaded!');
alert('Hello from external file!');

Script Placement: Where to Put <script> Tags?

The location of your <script> tag affects when the JavaScript executes.

📍 In <head>

Loads before the page content

<head>
  <script src="script.js"></script>
</head>

⚠️ May slow down page loading

✅ Before </body> (Recommended)

Loads after page content

<body>
  <!-- Page content -->
  <script src="script.js"></script>
</body>

✅ Faster page loading, DOM is ready

Defer and Async Attributes

Modern attributes that control how scripts load and execute.

HTML
CSS
JS

Attribute Comparison

Attribute When It Runs Use Case
defer After HTML parsing Most scripts
async As soon as downloaded Analytics, ads
None Immediately Critical scripts
Best Practice: Place scripts at the end of <body> or use defer attribute for better page load performance!

Summary

  • Use <script> tag to add JavaScript
  • Three methods: inline, internal, external
  • External files are best for larger projects
  • Place scripts before </body> for better performance
  • Use defer for scripts that need the full DOM

Quick Quiz

Where is the best place to put script tags for optimal page loading?

A
In the <head> section
B
Before </body> tag
C
After </html> tag
D
In a CSS file