Course contentsShow
← JavaScript
Lesson 22 of 2,7231. JavaScript FoundationsFree lesson

Creating an HTML File with Inline Script

Write a minimal HTML document and embed JavaScript using the <script> tag.

Creating an HTML File with Inline Script

What you'll learn: How to write a simple HTML file and embed JavaScript directly inside it using the <script> tag.

Why HTML and JavaScript Together?

When you run JavaScript in the browser (as we explored in lesson 21), you need an HTML document to hold your code. Think of HTML as the container and JavaScript as the instructions that make things happen inside that container.

Writing Your First HTML File with JavaScript

Here's a minimal HTML document with embedded JavaScript:

<!DOCTYPE html>
<html>
<head>
    <title>My First JavaScript Page</title>
</head>
<body>
    <h1>Hello, JavaScript!</h1>
    
    <script>
        console.log("This JavaScript runs in the browser!");
    </script>
</body>
</html>

Breaking It Down

  • <!DOCTYPE html> tells the browser this is an HTML5 document
  • <html>, <head>, and <body> are the basic structure every HTML page needs
  • The <script> tag is where your JavaScript lives
  • Everything between <script> and </script> is JavaScript code that the browser's engine (V8, SpiderMonkey, or JavaScriptCore) will execute

Where to Place the Script Tag

You can put <script> tags in the <head> or <body>. Placing it at the end of <body> (like above) ensures the HTML content loads before JavaScript runs—a common best practice.

Try It Yourself

Save this code as index.html, then open it in your browser. Right-click, select "Inspect," open the Console tab, and you'll see your message appear. This is inline scripting—the JavaScript is written directly inside the HTML file.

Key Takeaway: An HTML file provides the structure for running JavaScript in the browser, and the <script> tag is where you embed your JavaScript code directly into that document.