The Wayback Machine - https://web.archive.org/web/20241127203931/https://www.geeksforgeeks.org/where-to-put-javascript-in-an-html-document/
Open In App

How to Add JavaScript in HTML Document?

Last Updated : 15 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

To add JavaScript in HTML document, several method 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.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Inline JavaScript
    </title>
</head>

<body>
    <h2>
        Adding JavaScript in HTML Document
    </h2>

    <button onclick="alert('Button Clicked!')">
        Click Here
    </button>
</body>

</html>

Output

Inline-JavaScript

For a more comprehensive guide on integrating JavaScript with HTML, explore our JavaScript Course, which covers everything from basic scripting to building interactive and dynamic web pages.

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.

Example: This example shows the addition of a script file inside the head section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Add JavaScript Code inside Head Section
    </title>

    <script>
        function myFun() {
            document.getElementById("demo")
                .innerHTML = "Content changed!";
        }
    </script>
</head>

<body>
    <h2>
        Add JavaScript Code
        inside Head Section
    </h2>

    <h3 id="demo" style="color:green;">
        GeeksforGeeks
    </h3>

    <button type="button" onclick="myFun()">
        Click Here
    </button>
</body>

</html>

Output

JavaScript inside the <head> example output” width=”460″ height=”204″ loading=”lazy”></p>
<h3 id=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.

Example: This example shows showing the addition of a script file inside the body section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Add JavaScript Code inside Body Section
    </title>
</head>

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

</html>

Output

JavaScript inside <Body> example output” width=”460″ height=”204″ loading=”lazy”></p>
<h2 id=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.

Example: This example shows showing the linking of an external script file inside the head section.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        External JavaScript
    </title>
    <script src="script.js"></script>
</head>

<body>
    <h2>
        External JavaScript
    </h2>

    <h3 id="demo" style="color:green;">
        GeeksforGeeks
    </h3>

    <button type="button" onclick="myFun()">
        Click Here
    </button>
</body>

</html>
JavaScript
/* Filename: script.js*/

function myFun () {
    document.getElementById('demo')
        .innerHTML = 'Content Changed'
}

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>

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"


Previous Article
Next Article

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 specifying charset to UT
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 Content Method 1: JavaScr
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. Th
3 min read
HTML DOM document plugins Property
The HTML DOM plugins property returns an HTMLCollectionobject containing one or more embed elements or plugins of the current document. This is a read-only property. Syntax: objects = document.plugins Return value: An HTMLCollection object, or "null" object,if there are no embedded elements or plugins in the document. Example: This example shows ho
1 min read
How to specify an URL to a document that explains the reason why the text was deleted in HTML ?
The purpose of this article is to learn to specify a URL to a document that will explain, why the text was deleted. The HTML cite attribute specifies a URL to a document that explains the reason why the text was changed or deleted or inserted. The <del> tag in HTML is used to delete the text and mark a portion of the text which has been delet
1 min read
How to delete text from document using HTML ?
In this article, we delete text from an HTML document by using the <del> tag in the document. This tag stands for delete and is used to mark a portion of text which has been deleted from the document. Syntax: <del> Contents... </del> Example: In the following example, deletion of a text from a document is demonstrated. <!DOCTYP
1 min read
HTML DOM document contentType Property
The contentType property in HTML DOM returns the MIME type 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 this p
1 min read
HTML DOM document visibilityState Property
The visibilityState property returns the visibility of the document. This is a read-only property. Syntax: letvis = document.visibilityState; Return Value: visible: When page content may be visible to the user.hidden: When page content is not visible to the user.prerender: when the document is being prerendered and is not visible to the user. Examp
1 min read
HTML DOM document scrollingElement Property
The scrollingElement property of the document returns a reference to the element that scrolls the document. In standards mode, this is the root element of the document. Whereas in quirks mode, It returns the HTML body element or NULL. Syntax: let elem = document.scrollingElement; Return Value: In standards mode, It returns the root element of the d
1 min read
HTML DOM Document hidden Property
The Document hidden property returns a Boolean value indicating if the page is considered hidden or not. This is a read-only property. Syntax: let bool = document.hidden; Return Value: This property returns a Boolean Value. true if the page is considered hidden.false if the page is not considered hidden Example: This example shows how to use this p
1 min read
HTML DOM document location Property
The Document location property returns a Location of the document, that contains information about the URL of the document. This is a read-only property. Syntax: loc = document.location; Return Value: This property returns the string URL location of the document. Example: In this example, we will learn how to get the Document Location URL using thi
1 min read
HTML DOM window document Property
The HTML DOM window document returns a reference to the document contained in the current window. Syntax: doc = window.document; Return Value: This property returns a reference to the document. Example: In this example, we will get the title of the document using that document reference. C/C++ Code <title>Window document property</title
1 min read
How to embed audio element in a HTML document ?
Since the release of HTML5, audio can be added to webpages using the <audio> tag. Previously audio could be only played on webpages using web plugins like Flash. The <audio> tag is an inline element which is used to embed sound files into a web page. It is a very useful tag if you want to add audio such as songs, interviews, etc on your
1 min read
How to write address in an HTML document ?
The <address> tag in HTML is used to write contact information of a person or an organization. If <address> tag is used inside the <body> tag then it represents the contact information of the document and if the <address> tag is used inside the <article> tag, then it represents the contact information of the article. T
1 min read
How to write articles in HTML document ?
The <article> tag is one of the new sectioning element in HTML5. The HTML <article> tag is used to represent an article. More specifically, the content within the <article> tag is independent from the other content of the site (even though it can be related). In other words, the article element represents a component of a page tha
1 min read
How to create an HTML document which uses aside element ?
The <aside> tag is used to describe the main object of the web page in a shorter way like a highlighter. It basically identifies the content that is related to the primary content of the web page but does not constitute the main intent of the primary page. The <aside> tag contains mainly author information, links, related content and so
2 min read
How to define header for a document or section using HTML ?
The <header> tag in HTML is used to define the header for a document or a section. It contains information related to the title and heading of the related content. The <header> element is intended to usually contain the section’s heading (an h1-h6 element or an <hgroup> element), but this is not required. The <header> elemen
2 min read
How to define information about the document using HTML ?
The <head> tag in HTML is used to define the head portion of the document which contains metadata related to the document. This tag can contain other head elements such as <title>, <meta>, <link>, <style>, <link> etc. The <head> element was mandatory In HTML 4.01, but it can be omitted in the current HTML 5
1 min read
How to define the root of an HTML document ?
The <html> tag in HTML is used to define the root of HTML and XHTML documents. The <html> tag tells the browser that it is an HTML document. It is the second outer container for everything that appears in an HTML document followed by the <!DOCTYPE> tag. The <html> tag requires a starting and end tag. Syntax: <html> HTM
1 min read
How to define metadata about an HTML document in HTML5 ?
The metadata means the information about data. The <meta> tag in HTML provides information about HTML Document or in simple words, it provides important information about a document. These tags are basically used to add name/value pairs to describe properties of HTML documents, such as expiry date, author name, list of keywords, document auth
1 min read
Different ways to apply colors in an HTML document
A colorful website or application is more attractive rather than a black-and-white website. In this article, we will go through all the different ways to apply colors in HTML documents. Like other HTML tags, there is no special tag to apply colors in HTML documents. However, using the style attribute, you can make a particular element colorful and
5 min read
How to indicate character set being used by a document in HTML ?
For web browser to understand the set of characters used in the HTML document, various HTML encoding character set representations has been used like ASCII, ISO-8859-1, UTF-8 etc. The character set being used by an HTML document is indicated using the charset attribute of a <meta> tag inside the <head> element of the HTML. In HTML4, ISO
2 min read
Which tag is used to define the header for HTML document ?
The <header> tag in HTML is used to define the header for a document. It contains information related to the title and heading of the related content. The <header> element is intended to usually contain the section’s heading (an h1-h6 element or an <hgroup> element), but this is not required. The <header> element can also be
2 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 access an HTML document in a browser ?
HTML represents Hypertext Markup Language and is web - based scripting language. Its primary object is to make and design website pages. Records with the HTML (or HTM) augmentation just hold back text and references to different documents, similar to pictures or video. How to access an HTML file in the browser: There are a wide range of projects th
3 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
three90RightbarBannerImg