Adding JavaScript to HTML Pages

JavaScript can be placed directly in an HTML <script> element or loaded from an external .js file. For most real pages, external scripts are easier to maintain and cache, while a small inline script can be appropriate for a tightly scoped task.

Basic inline structure:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>JavaScript Structure</title>
</head>
<body>
  <p id="message">Waiting...</p>
  <script>
    document.getElementById("message").textContent = "Hello World";
  </script>
</body>
</html>

The browser parses the HTML and executes the script when it reaches the <script> element unless loading attributes such as defer, async, or type="module" change that behavior.

Adding JavaScript with the script Element Top ↑

The <script> element tells the browser that its contents are JavaScript. In HTML5, a normal JavaScript block does not need language="JavaScript" or type="text/javascript".

<script>
  const message = "Hello World";
  console.log(message);
</script>

The original version of this tutorial used document.write() to demonstrate immediate execution. For current pages, use the console or DOM methods instead so the document is not unexpectedly replaced.

Using an External JavaScript File Top ↑

Put reusable code in a separate file and load it with src. Do not place JavaScript code between the opening and closing tags when src is being used for the script you want to execute.

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

An external file named app.js contains JavaScript only:

const siteName = "plus2net";
console.log(siteName);

Should script Be in the head or body? Top ↑

A classic script without special attributes blocks HTML parsing while it is fetched and executed. Placing such a script near the end of <body> allows earlier HTML to be parsed first. For scripts in <head>, defer is often the cleaner option when the script depends on the page DOM.

<head>
  <script src="app.js" defer></script>
</head>

A script placed after the element it uses can also access that element immediately:

<p id="status">Waiting...</p>
<script>
  document.getElementById("status").textContent = "Ready";
</script>

Using defer for External Scripts Top ↑

defer downloads a classic external script without blocking HTML parsing and executes deferred scripts after the document has been parsed, in document order, before DOMContentLoaded.

<script src="library.js" defer></script>
<script src="app.js" defer></script>

Use defer when order matters and the code should run after the HTML has been parsed.

Using async Top ↑

async also downloads an external classic script without blocking the download phase, but it executes as soon as it is ready. Execution order between multiple async scripts is not guaranteed.

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

This is useful for independent scripts such as some analytics integrations. Do not use async for scripts that depend on each other unless the dependency is managed another way.

Using JavaScript Modules Top ↑

Modules support import and export, have their own module scope, and are deferred by default. Use type="module".

<script type="module" src="app.js"></script>
// app.js
import { formatName } from "./utils.js";
console.log(formatName("plus2net"));

Module scripts follow CORS rules when loaded across origins, so server configuration matters when files come from another domain.

Running Code After the DOM Is Ready Top ↑

Older pages often call a function with an inline onload attribute on <body>. A modern alternative is an event listener.

document.addEventListener("DOMContentLoaded", () => {
  console.log("HTML has been parsed");
});

If the script is deferred, a separate DOMContentLoaded listener is often unnecessary for simple DOM setup because the document has already been parsed before the deferred script runs.

Script Attributes You Usually Do Not Need Top ↑

  • language="JavaScript" is obsolete and should not be used.
  • type="text/javascript" is unnecessary for ordinary JavaScript in HTML5.
  • Use type="module" specifically when the script is a JavaScript module.
  • Use src for an external file, and use defer or async only when their loading behavior matches the requirement.

When JavaScript Is Unavailable Top ↑

Pages should keep essential information and navigation usable when possible. The HTML <noscript> element can provide a message when scripting is disabled or unavailable.

<noscript>This interactive example requires JavaScript.</noscript>

See JavaScript support and browser settings for the older support-focused tutorial.

Safe JavaScript and HTML Integration Top ↑

Prefer textContent for plain text. Avoid inserting untrusted strings with innerHTML, and avoid dynamically constructing executable code. If a page accepts user input, validate it for the application requirement and perform security-sensitive validation on the server as well.

Common JavaScript Structure Mistakes Top ↑

  • Using obsolete language attributes copied from old examples.
  • Loading dependent files with async and assuming they will execute in order.
  • Running DOM code before the target element exists.
  • Using document.write() as a general page-update method.
  • Putting large reusable programs inline instead of maintaining an external file.
  • Forgetting that module scripts and classic scripts have different scope and loading behavior.

Continue with JavaScript variables, alert dialogs, the HTML script element, and HTML code structure.

JavaScript Basic Variables




Subscribe to our YouTube Channel here



plus2net.com







mari

08-02-2010

i need validation for name, email, phone number...
shushrita

01-09-2013

'text/JavaScript'.This is no longer required. JavaScript is the default scripting language in all modern browsers.



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer