Understanding the <script> Element
The <script> element allows JavaScript to be included in an HTML document or connects the document to an external JavaScript file.
JavaScript can add behavior and interactivity to a webpage, such as responding to user actions, changing page content, validating information, or performing other tasks. HTML provides the structure, CSS controls the presentation, and JavaScript can control how the page behaves.
<script> Element Syntax
The script element can contain JavaScript code directly within an HTML document.
<script>
JavaScript code
</script>
The script element has both a start tag and an end tag. Unlike void elements such as meta and link, the closing </script> tag is required.
For example:
<script>
console.log("Hello, World!");
</script>
The browser processes the JavaScript contained between the two tags.
Where to Place the <script> Element
The script element can be used in the document's head or body, depending on how the script is intended to load and run.
A script can be placed in the document head:
<head>
<meta charset="utf-8">
<title>My Webpage</title>
<script>
console.log("JavaScript is running.");
</script>
</head>
It can also appear within the document body:
<body>
<h1>My Webpage</h1>
<script>
console.log("JavaScript is running.");
</script>
</body>
Where a script is placed can affect when it runs in relation to the browser processing the surrounding HTML. Later in this tutorial, you will see how the defer attribute can make loading external scripts from the document head more convenient.
Internal JavaScript
JavaScript written directly between the start and end tags of a script element is sometimes called internal or embedded JavaScript.
<script>
document.querySelector("h1").textContent = "Hello from JavaScript!";
</script>
This JavaScript finds the first h1 element in the document and changes its text content.
Internal JavaScript can be useful for small examples, demonstrations, or scripts that belong only to a particular document.
Using JavaScript in the <script> Element
JavaScript can respond to actions performed by the user and make changes to the HTML document after the page has loaded.
For example, JavaScript can listen for a button click and then change text on the page:
<p id="message">Click the button to change this text.</p>
<button type="button" id="change-text">Change Text</button>
<script>
const button = document.querySelector("#change-text");
const message = document.querySelector("#message");
button.addEventListener("click", function () {
message.textContent = "The text was changed with JavaScript!";
});
</script>
The HTML creates the paragraph and button, while JavaScript adds the behavior that occurs when the button is selected.
Try the example below. Change the text in the HTML or JavaScript, and then use the button to see how JavaScript can interact with page content.
External JavaScript
JavaScript can also be stored in a separate file rather than written directly inside the HTML document.
An external JavaScript file normally uses the .js filename extension:
script.js
The JavaScript file contains JavaScript code without the HTML <script> tags:
console.log("Hello from an external JavaScript file!");
The HTML document connects to the external file using the src attribute on the script element:
<script src="/js/script.js"></script>
External JavaScript files are especially useful when the same code is used by multiple webpages because the script can be maintained in one file.
The src Attribute
The src attribute specifies the URL of an external JavaScript resource.
<script src="/js/script.js"></script>
The URL can be relative, root-relative, or absolute, depending on where the JavaScript file is located.
Relative URL
<script src="js/script.js"></script>
Root-Relative URL
<script src="/js/script.js"></script>
Absolute URL
<script src="https://www.example-web.site/js/script.js"></script>
When the src attribute is present, the contents between the script element's start and end tags are not used as an additional block of JavaScript. Keep the external script reference and internal JavaScript in separate script elements.
<script src="/js/script.js"></script>
<script>
console.log("Additional JavaScript");
</script>
The defer Attribute
The defer attribute can be used with a classic external script so the browser can continue processing the HTML document while the script is being downloaded.
<script src="/js/script.js" defer></script>
A deferred script runs after the HTML document has been parsed and before the document's DOMContentLoaded event occurs.
This makes defer useful when an external script is placed in the document head but needs to work with elements in the page body.
<head>
<meta charset="utf-8">
<title>My Webpage</title>
<script src="/js/script.js" defer></script>
</head>
The defer attribute is boolean, so its presence enables the behavior. Writing simply defer is the preferred form.
Head vs Body Placement
You will encounter scripts placed both in the document head and near the end of the document body.
An external script in the head can use defer:
<head>
<script src="/js/script.js" defer></script>
</head>
A script can also be placed after the page content near the end of the body:
<body>
<h1>My Webpage</h1>
<p>Page content goes here.</p>
<script src="/js/script.js"></script>
</body>
Placing a script after the content means the browser has already encountered the preceding HTML before reaching the script. Using defer with an external classic script in the head allows the browser to discover the script earlier without requiring it to execute before the document has finished being parsed.
There are additional script-loading options, including modules and asynchronous scripts, but those are better covered when learning JavaScript in greater detail.
When JavaScript Is Unavailable
JavaScript may occasionally be disabled, blocked, fail to load, or encounter an error that prevents a script from running.
Whenever practical, important page content and basic navigation should not depend entirely on JavaScript when ordinary HTML can provide the underlying functionality.
HTML should provide meaningful structure and content first, with JavaScript added when behavior or interactivity is needed. This approach can make webpages more resilient and easier to use across different browsing conditions.
HTML also provides the noscript element for content that can be shown when scripting is disabled or otherwise unavailable in supported circumstances.
<noscript>
<p>JavaScript is required for this feature.</p>
</noscript>
Complete JavaScript Example
The following document contains a small internal script that changes a message when the user selects a button:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JavaScript Example</title>
</head>
<body>
<h1>JavaScript Example</h1>
<p id="message">Click the button to change this text.</p>
<button type="button" id="change-text">Change Text</button>
<script>
const button = document.querySelector("#change-text");
const message = document.querySelector("#message");
button.addEventListener("click", function () {
message.textContent = "Hello from JavaScript!";
});
</script>
</body>
</html>
The HTML provides the heading, paragraph, and button. The JavaScript finds the paragraph and button and then changes the paragraph's text when the button is selected.
Common <script> Element Mistakes
JavaScript may fail to run when the script element, external file path, or JavaScript code contains an error.
- Forgetting the closing
</script>tag. - Using an incorrect URL in the
srcattribute. - Including HTML
<script>tags inside an external.jsfile. - Trying to combine an external script and additional JavaScript inside the same
scriptelement. - Running JavaScript before the HTML elements it needs are available.
- Assuming every script should use the same loading method or placement.
- Making essential content unnecessarily dependent on JavaScript.
Browser developer tools, particularly the Console, are useful for finding JavaScript errors when a script does not behave as expected.
<script> Element Best Practices
JavaScript is easier to maintain when scripts are organized clearly and added only where behavior or interactivity is needed.
- Use HTML for document structure and content before adding JavaScript behavior.
- Use external JavaScript files when code needs to be shared across multiple pages.
- Use accurate paths in the
srcattribute. - Consider
deferfor classic external scripts placed in the document head when they depend on the parsed document. - Keep internal scripts organized and readable.
- Avoid mixing HTML markup into external JavaScript files.
- Use browser developer tools when troubleshooting script errors.
- Do not add JavaScript when ordinary HTML already provides the required functionality.
Using JavaScript as an enhancement to well-structured HTML helps keep webpages understandable, maintainable, and resilient.
Summary
The script element adds JavaScript to an HTML document or connects the document to an external JavaScript file. JavaScript can respond to user actions, modify page content, and add behavior that HTML alone does not provide.
JavaScript can be written directly inside a script element or stored in an external .js file referenced with the src attribute. Script placement and loading behavior affect when JavaScript runs, so scripts should be added deliberately while keeping the underlying HTML structure clear and usable.
