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:
-
Internal JavaScript
-
External JavaScript
-
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:
Here:
-
script.jsis an external file -
Code is written inside that file
-
HTML remains clean and organized
-
This is the best practice
Your external JS example code:
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:
-
Browser loads HTML
-
Browser reads CSS
-
Browser reads JavaScript
-
JavaScript runs line-by-line (top to bottom)
-
Output is displayed on the screen
Functions like:
write content directly to the webpage.
Example outputs from your code:
-
Text values
-
Headings
<h1> -
Paragraph
<p> -
Numbers
-
Data types using
typeof
Example:
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.