How to Embed JavaScript in HTML

JavaScript is the most popular scripting language used to make web pages interactive and dynamic. HTML creates the structure, CSS adds styling, and JavaScript adds life to the page. In this blog, you will learn how to embed JavaScript in HTML and how it actually works inside the browser.

Ways to Embed JavaScript in HTML

There are three main ways to add JavaScript to an HTML page:

  1. Internal JavaScript

  2. External JavaScript

  3. Inline JavaScript

Let’s understand each of them with examples.

1. Internal JavaScript

Internal JavaScript is written inside the HTML file using the <script> tag.

<script>
document.write(“Hello JavaScript”);
</script>

This script runs when the browser loads the page and prints text on the screen.

2. External JavaScript

External JavaScript is written in a separate .js file and linked to HTML using src attribute.

Your HTML example:

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

Here:

  • script.js is an external file

  • Code is written inside that file

  • HTML remains clean and organized

  • This is the best practice

Your external JS example code:

document.write("External Javascript File");

document.write("<h1>Hello World</h1>");
document.write("<h1>Javascript is a scripting Language</h1>");

document.write("<p>Client Side scripting language</p>");

This code will output text and headings directly in the browser.

3. Inline JavaScript

Inline JavaScript is written inside HTML tags.

Example:

<button
onclick="alert('Hello')">Click Me</button>

Used for small events, not recommended for big projects.

How JavaScript Works in the Browser

When you open a webpage:

  1. Browser loads HTML

  2. Browser reads CSS

  3. Browser reads JavaScript

  4. JavaScript runs line-by-line (top to bottom)

  5. Output is displayed on the screen

Functions like:

document.write()

write content directly to the webpage.

Example outputs from your code:

  • Text values

  • Headings <h1>

  • Paragraph <p>

  • Numbers

  • Data types using typeof

Example:

document.write(typeof("Aptech")); // string

document.write(typeof(122223331)); // number

document.write(typeof(true)); // boolean

document.write(typeof(null)); // object

document.write(typeof(["Ali","Raza","Ahmed"])); // object


Conclusion

Embedding JavaScript in HTML is easy. You can use:

  • Internal script tags

  • External script files

  • Inline scripts

External JavaScript is preferred because it keeps code clean and reusable.

My GitHub Repository for JavaScript Code

All example codes related to JavaScript data types and variables are available in my GitHub repository:

JavaScript Codes – My GitHub Repo

You can open the files, study the code, and run them in your browser.


Read More

To understand the basics first, read my complete guide on Introduction to JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

Categories: