Javascript Notes4
Javascript Notes4
geeksforgeeks
Courses
Tutorials
HTML/CSS
JavaScript
Sign In
GfG 160
Share Your Experiences
JavaScript Tutorial
JavaScript Basics
Introduction to JavaScript
JavaScript Versions
How to Add JavaScript in HTML Document?
JavaScript Syntax
JavaScript Output
JavaScript Comments
JS Variables & Datatypes
JS Operators
JS Statements
JS Loops
JS Perfomance & Debugging
JS Object
JS Function
JS Array
JS String
JS Numbers
JS Math
JS Map
JS Set
JS Objects
JS Advance
JavaScript Exercises
Full Stack DevelopmentCourse
How to Add JavaScript in HTML Document?
Last Updated : 10 Jan, 2025
To add JavaScript in HTML document, several methods can be used. These methods
include embedding JavaScript directly within the HTML file or linking an external
JavaScript file.
Inline JavaScript
You can write JavaScript code directly inside the HTML element using the onclick,
onmouseover, or other event handler attributes.
{...}
{...}
Internal JavaScript (Within <script> Tag)
You can write JavaScript code inside the <script> tag within the HTML file. This is
known as internal JavaScript and is commonly placed inside the <head> or <body>
section of the HTML document.
{...}
<head>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</head>
{...}
2. JavaScript Code Inside <body> Tag
JavaScript can also be placed inside the <body> section of an HTML page. Typically,
scripts placed at the end of the <body> load after the content, which can be useful
if your script depends on the DOM being fully loaded.
{...}
<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>
<h3 id="demo" style="color:green;">
GeeksforGeeks
</h3>
<button type="button" onclick="myFun()">
Click Here
</button>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</body>
{...}
External JavaScript (Using External File)
For larger projects or when reusing scripts across multiple HTML files, you can
place your JavaScript code in an external .js file. This file is then linked to
your HTML document using the src attribute within a <script> tag.
{...}
<head>
<script src="script.js"></script>
</head>
{...}
Output:
1. async Attribute
The async attribute loads the script asynchronously, meaning the script will be
downloaded and executed as soon as it is available, without blocking the page.
Master DSA with JavaScript in just 90 days. Explore core DSA concepts, refine your
coding skills, and tackle real-world challenges. Take on the Three 90 Challenge—
complete 90% of the course in 90 days and earn a 90% refund as a reward for your
commitment!
Comment
More info