Skip to main content
March 23, 2026Dan Rodney/4 min read

External JS Files: Sharing JavaScript Across Pages

Master JavaScript modularity and code reusability techniques

Key JavaScript Development Concepts

Code Reusability

Write once, use everywhere. External JavaScript files eliminate code duplication and make maintenance efficient across multiple pages.

Modular Architecture

Separating JavaScript into external files creates cleaner, more organized code structure that scales with project growth.

Dynamic Functionality

Smart coding techniques allow the same JavaScript to work across different products and contexts without modification.

Topics Covered in This JavaScript Tutorial:

Externalizing JavaScript, Linking to the JavaScript File

Exercise Preview

preview externalizing js

Learning Objective

This tutorial demonstrates transforming embedded JavaScript into reusable external files, using a product color chooser that works across multiple webpage types.

Exercise Overview

In this exercise, you'll master a fundamental JavaScript best practice: externalizing your code into reusable modules. By moving JavaScript from inline script tags into external files, you'll create maintainable, scalable solutions that can power multiple webpages efficiently. This approach is essential for modern web development, where code reusability and clean architecture separate professional applications from amateur implementations.

Getting Started

Let's begin by setting up your development environment and examining the existing code structure.

  1. For this exercise we'll be working with the Sharing-JavaScript folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  2. In your code editor, open chair.html from the Sharing-JavaScript folder.
  3. Preview chair.html in a web browser.

This is the product color chooser you completed in the previous exercise—a fully functional interactive component that demonstrates JavaScript's power in creating dynamic user experiences.

  1. Switch back to your code editor.
  2. Open wall-clock.html from the Sharing-JavaScript folder.
  3. Preview the page in a browser.

    Notice this page has identical styling and structure, complete with a color chooser interface, but the interactive functionality is missing—the buttons don't respond because no JavaScript has been implemented yet.

    Rather than duplicating our existing code (a violation of the DRY principle—Don't Repeat Yourself), we'll demonstrate how to architect reusable JavaScript that can power unlimited product pages while maintaining a single source of truth.

Project Setup Requirements

1

Locate Project Files

Open the Sharing-JavaScript folder from Desktop > Class Files > JavaScript Class in your code editor

2

Examine Existing Pages

Review chair.html with working color chooser and wall-clock.html without JavaScript functionality

3

Identify Code Duplication

Recognize the need to share JavaScript functionality between multiple product pages

Externalizing JavaScript

Code duplication is the enemy of maintainable software. When JavaScript lives directly in HTML files, every update requires hunting down and modifying multiple locations—a recipe for bugs and inconsistencies. By externalizing our JavaScript into dedicated .js files, we create a centralized codebase that's easier to debug, update, and scale. This practice is standard across professional development teams and essential for any serious web application.

  1. Switch back to your code editor.
  2. Switch back to chair.html.
  3. Find the script tag at the bottom.
  4. Select all the code between the opening and closing script tags. Do not select the <script> and </script> tags themselves!

    <script>
       let productPhoto = document.getElementById('product-photo');

    Code Omitted To Save Space

    }
    </script>
  5. Cut the code (Ctrl+X or Cmd+X).

  6. Create a new file in your editor.

  7. Paste the JavaScript code into this new file.

  8. Save the file as main.js into the js folder within the Sharing-JavaScript directory.

You've now created your first external JavaScript module—a standalone file that can be linked to any HTML page requiring this functionality.

External JavaScript Files vs Inline Code

Pros
Single source of truth eliminates duplicate code
Easy to update functionality across all pages
Cleaner HTML structure with separated concerns
Better browser caching for improved performance
Cons
Additional HTTP request for external file
Requires proper file path management
May need modifications for page-specific functionality
Critical Implementation Detail

When extracting JavaScript code, copy only the content between script tags, not the opening and closing script tags themselves.

Linking to the JavaScript File

With our JavaScript externalized, we need to establish the connection between our HTML documents and the new .js file. This linking process tells the browser where to find and execute our code.

  1. Switch back to chair.html.
  2. Modify the script tags as shown below, ensuring you remove any content between the opening and closing tags:

    <script src="js/main.js"></script>
    </body>
  3. Save and preview chair.html in a browser.

Test the color selection buttons—they should function exactly as before. This confirms that external JavaScript files execute with the same capabilities as inline code, but with significantly better organization.

  1. Switch back to your code editor.
  2. Switch to wall-clock.html.
  3. At the bottom of the document, immediately before the closing </body> tag, add the following code:

    <script src="js/main.js"></script> 
    </body>
  4. Save the file.

Script Tag Implementation Methods

FeatureInline JavaScriptExternal JavaScript
Code LocationInside HTML fileSeparate .js file
HTML Syntax<script>code here</script><script src="path/file.js"></script>
ReusabilitySingle page onlyMultiple pages
MaintenanceUpdate each pageUpdate one file
Recommended: External JavaScript files provide superior maintainability and code organization for multi-page projects.

Making the Code Work for Any Product

Currently, our color chooser contains hardcoded references to the "chair" product, limiting its reusability. Professional JavaScript applications use dynamic approaches that adapt to different contexts automatically. We'll refactor our code to detect the product type programmatically, creating truly flexible functionality.

  1. In wall-clock.html, locate the image element with id product-photo.

    Observe that it includes a class attribute set to wall-clock, while the corresponding element in chair.html uses chair. This class name serves as our product identifier—a semantic approach that makes our HTML self-documenting and our JavaScript context-aware.

  2. Switch to main.js in your editor.
  3. Within the changeColor() function, replace the hardcoded "chair" reference with dynamic class detection:

    productPhoto.src = 'img/' + productPhoto.className + '-' + this.id + '.jpg';

    NOTE: Pay careful attention to the single quotes and plus operators—JavaScript string concatenation requires precise syntax.

  4. Save the file.
  5. Preview wall-clock.html in a browser.

    Hover over the color buttons—they now respond dynamically, loading the appropriate wall-clock images based on your selections.

  6. Test chair.html in your browser to verify it continues working flawlessly.

Congratulations! You've successfully created a scalable, reusable JavaScript component that exemplifies modern development practices. This pattern—externalizing code, using semantic HTML attributes for context, and writing dynamic rather than hardcoded solutions—forms the foundation of professional web applications that can grow and adapt over time.

productPhoto.src = 'img/ ' + productPhoto.className + ' -' + this.id + '.jpg';
Dynamic path construction using className property enables the same JavaScript to work with different product types by reading the CSS class as the product identifier.

Code Flexibility Implementation

0/4

Key Takeaways

1External JavaScript files eliminate code duplication by allowing multiple HTML pages to share the same functionality
2The src attribute in script tags links HTML files to external JavaScript files using relative file paths
3Moving JavaScript from inline script tags to external files requires copying only the code content, not the script tags themselves
4Dynamic programming techniques using element properties like className make JavaScript adaptable across different page contexts
5Proper file organization with dedicated js folders creates maintainable project structures for web development
6Testing functionality after externalizing code ensures that the refactoring process maintains all intended behaviors
7String concatenation in JavaScript enables dynamic file path construction for flexible image and resource loading
8External JavaScript files improve code maintainability by creating a single source of truth for shared functionality

RELATED ARTICLES