0% found this document useful (0 votes)
7 views9 pages

Javascript Notes4

The document explains various methods to add JavaScript to an HTML document, including inline, internal, and external JavaScript. It highlights the advantages of using external JavaScript files, such as faster load times and improved readability. Additionally, it discusses the use of async and defer attributes to optimize script loading performance.

Uploaded by

Bharath
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
7 views9 pages

Javascript Notes4

The document explains various methods to add JavaScript to an HTML document, including inline, internal, and external JavaScript. It highlights the advantages of using external JavaScript files, such as faster load times and improved readability. Additionally, it discusses the use of async and defer attributes to optimize script loading performance.

Uploaded by

Bharath
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 9

Skip to content

geeksforgeeks
Courses
Tutorials
HTML/CSS
JavaScript

Sign In

DSA with JS - Self Paced


JS Tutorial
JS Exercise
JS Interview Questions
JS Array
JS String
JS Course
JS Object
JS Operator
JS Date
JS Error
JS Projects
JS Set
JS Map
JS RegExp
JS Math
JS Number
JS Boolean
JS Examples
JS Free JS Course
JS A to Z Guide
JS Formatter

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.

{...}

<button onclick="alert('Button Clicked!')">


Click Here
</button>

{...}
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.

1. JavaScript Code Inside <head> Tag


Placing JavaScript within the <head> section of an HTML document ensures that the
script is loaded and executed as the page loads. This is useful for scripts that
need to be initialized before the page content is rendered.

{...}

<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:

External JavaScript example output

Advantages of External JavaScript


Faster Page Load Times: Cached external JavaScript files don’t need to be reloaded
every time the page is visited, which can speed up loading times.
Improved Readability and Maintenance: Keeping HTML and JavaScript separate makes
both easier to read and maintain.
Separation of Concerns: By separating HTML (structure) and JavaScript (behavior),
your code becomes cleaner and more modular.
Code Reusability: One external JavaScript file can be linked to multiple HTML
files, reducing redundancy and making updates easier.
Asynchronous and Deferred JavaScript
JavaScript can be loaded asynchronously or deferred to optimize page performance,
especially for larger scripts. By default, JavaScript blocks the rendering of the
HTML page until it is fully loaded, but using async or defer can help improve load
times.

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.

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


2. defer Attribute
The defer attribute delays the execution of the script until the entire HTML
document has been parsed. This is particularly useful for scripts that manipulate
the DOM.
<script src="script.js" defer></script>
To read more about defer follow the article – HTML defer Attribute

How to Reference External JavaScript Files?


We can reference an external script in three ways in javascript:

By using a full URL:


src = "https://www.geeksforgeek.org/js/script.js"
By using a file path:
src = "/js/script.js"
Without using any path:
src = "script.js"

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

Placement Training Program


Next Article
JavaScript Syntax
Similar Reads
How to fix “No character encoding declared at document level” in HTML Document ?
This article intends to solve the “No character encoding declared at document
level” issue in your HTML program. So, before getting to the solution, we need to
understand what this issue means. And for that first, we need to know about
character encoding in HTML. What is character encoding in HTML? Character encoding
is a system used to represent c
5 min read
How to add emoji in HTML document ?
Emojis are the characters from the Unicode character set that look like images or
icons ????????????‍♂️
. They can be sized, copied, or pasted like any other character
in HTML. UTF-8 is the default charset that is used in HTML documents because it
contains almost all of the characters and symbols. Emojis can be inserted in HTML
documents by specifyi
3 min read
HTML Course | Structure of an HTML Document
When building web pages, understanding the basic structure of an HTML document is
the first step. The structure not only provides a framework for the document but
also enables browsers to render content correctly. HTML(Hypertext Markup Language),
structures web pages. Unlike programming languages, it isn't compiled or
interpreted. Browsers render H
4 min read
How to Get the Entire HTML Document as a String Using JavaScript?
We will explore how to retrieve the entire HTML document as a string using
JavaScript. This can be useful when you want to inspect or manipulate the entire
structure of a webpage.Methods to Get the Entire HTML Document as a StringThere are
two primary methods for extracting the HTML content of a page as a string:Table of
ContentMethod 1: JavaScript
2 min read
How to Display Word Document in HTML using JavaScript?
Displaying Word documents in HTML is a valuable feature for web applications,
enabling users to view content without needing to download files. JavaScript
provides several tools and libraries to facilitate this process, making it easier
to convert and render .docx files directly in the browser. This capability is
particularly useful for educational
4 min read
How to add footer for a document or section using HTML5 ?
In this article, we define a footer for a document or section by using the <footer>
tag. This tag in HTML is used to define a footer of HTML document. This section
contains the footer information (author information, copyright information,
carriers, etc). The <footer> tag is used within the body tag. The footer tag is new
in the HTML5.
1 min read
How are the JavaScript window and JavaScript document different from one another?
What is a JavaScript window? The window is at a root/top level at the JavaScript
object hierarchy. It is a global/root object in JavaScript and it is the root
object of the Document object model(DOM); What is a JavaScript document? A document
is an object inside the window object and we use a document object for manipulation
inside the document. T
3 min read
Which property can be used to return the doctype of any HTML document ?
The document.contentType property in HTML DOM returns the doctype in which the
document is being rendered. This is a read only property. Syntax: value =
document.contentType; Return value: This property returns a string value of MIME
content type of the document. Example: This example will show how to get the
content MIME Type of the document using
1 min read
How to return the currently active elements in the HTML document ?
In this article, we will discuss how to return the currently active element in an
HTML document. We will use the activeElement DOM property which will help us to
achieve so. The DOM activeElement property is used to return the currently active
elements in the HTML document. This property is read-only. It provides us with a
reference to a focused el
2 min read
How to include External CSS in an HTML Document ?
Adding External CSS in an HTML document is achieved using the <link> element in the
<head> section. This approach allows you to separate your HTML content and styling.
Here are some important points: Establishing Connection (rel attribute): The <link>
element uses the "rel" attribute to show how the HTML document is connected to t
1 min read
course-img
86k+ interested Geeks
MERN Full Stack Web Development
Explore
course-img
27k+ interested Geeks
Complete Backend Development Program- Mastering OOPS, Spring Boot, and
Microservices
Explore
course-img
72k+ interested Geeks
JavaScript Full Course Online | Learn JavaScript with Certification
Explore
course-img
52k+ interested Geeks
Data Structures & Algorithms in JavaScript - Self Paced Course
Explore
course-img
154 interested Geeks
Front-End Interview Preparation Course
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh
(201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar,
Uttar Pradesh, 201305
GFG App on Play Store
GFG App on App Store
Advertise with us
Company
About Us
Legal
Privacy Policy
Careers
In Media
Contact Us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning
ML Maths
Data Visualisation
Pandas
NumPy
NLP
Deep Learning
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
DSA/Placements
DSA - Self Paced Course
DSA in JavaScript - Self Paced Course
DSA in Python - Self Paced
C Programming Course Online - Learn C with Data Structures
Complete Interview Preparation
Master Competitive Programming
Core CS Subject for Interview Preparation
Mastering System Design: LLD to HLD
Tech Interview 101 - From DSA to System Design [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]
Development/Testing
JavaScript Full Course
React JS Course
React Native Course
Django Web Development Course
Complete Bootstrap Course
Full Stack Development - [LIVE]
JAVA Backend Development - [LIVE]
Complete Software Testing Course [LIVE]
Android Mastery with Kotlin [LIVE]
Machine Learning/Data Science
Complete Machine Learning & Data Science Program - [LIVE]
Data Analytics Training using Excel, SQL, Python & PowerBI - [LIVE]
Data Science Training Program - [LIVE]
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification
Programming Languages
C Programming with Data Structures
C++ Programming Course
Java Programming Course
Python Full Course
Clouds/Devops
DevOps Engineering
AWS Solutions Architect Certification
Salesforce Certified Administrator Course
GATE
GATE CS & IT Test Series - 2025
GATE DA Test Series 2025
GATE CS & IT Course - 2025
GATE DA Course 2025
GATE Rank Predictor
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like