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

External JavaScript Files

Link separate .js files to HTML using <script src="..."> for better code organization.

External JavaScript Files

What you'll learn: How to move your JavaScript code into separate .js files and link them to your HTML for cleaner, more organized projects.

Why Use External Files?

Instead of writing JavaScript directly inside <script> tags in your HTML (called "inline" script), you can store your code in separate files with a .js extension. This is like organizing your documents into different folders instead of keeping everything in one messy pile.

How It Works

Create a new file (for example, script.js) and write your JavaScript there. Then, in your HTML file, use the <script> tag with a src attribute to connect them:

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>Hello World</h1>
    
    <!-- Link to external JavaScript file -->
    <script src="script.js"></script>
</body>
</html>

In your script.js file, you'd write your JavaScript code without any <script> tags:

console.log("This code runs from an external file!");

Benefits of External Files

  • Organization: Keep HTML and JavaScript separate, making both easier to read
  • Reusability: Use the same .js file across multiple HTML pages
  • Maintainability: Update JavaScript in one place instead of hunting through HTML
  • Browser caching: External files can be cached, making your site faster for returning visitors

The src attribute works like a file path — it tells the browser where to find your JavaScript file. If the file is in the same folder as your HTML, just use the filename.

Key Takeaway: Use <script src="filename.js"></script> to link external JavaScript files to your HTML, keeping your code organized and maintainable as your projects grow.