Skip to main content
April 1, 2026Dan Rodney/4 min read

Sharing JavaScript Across Pages

Master JavaScript Modularity for Scalable Web Applications

Benefits of External JavaScript Files

Code Reusability

Write once, use across multiple pages. Eliminate duplicate code and maintain consistency throughout your application.

Easier Maintenance

Update JavaScript in one location to affect all pages. Reduces bugs and simplifies version control.

Better Performance

Browsers cache external JS files, reducing load times for subsequent page visits.

Topics Covered in This JavaScript & JQuery Tutorial:

Externalizing JavaScript, Linking to the JavaScript File

Exercise Preview

externalizing js preview

Exercise Overview

In this exercise, you'll master a fundamental development practice: externalizing JavaScript code into separate files. This approach enables code reusability across multiple pages while maintaining a single source of truth for your functionality. By the end of this exercise, you'll understand why external JavaScript files are essential for scalable web development and how they streamline maintenance workflows.

What We'll Accomplish

1

Identify the Problem

Recognize that accordion functionality works on index.html but not on photo-gallery.html due to missing JavaScript

2

Extract JavaScript

Move JavaScript code from HTML into a separate .js file for reusability

3

Link External File

Connect both HTML pages to the shared JavaScript file using script src attributes

Getting Started

Before we dive into externalizing JavaScript, let's set up our workspace and examine the current state of our files.

  1. Launch your code editor if it isn't already running.
  2. Close any open files to start with a clean workspace.
  3. Navigate to the Sharing-JavaScript folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. If your editor supports folder-based workflows (like Visual Studio Code, WebStorm, or Sublime Text), open this entire folder as a project for better file management.
  4. Open index.html from the Sharing-JavaScript folder.
  5. Preview the page in your browser. Notice the accordion functionality on the right side of the page—this is the interactive component you built in the previous exercise. Click through the accordion sections to verify it's functioning properly.
  6. Return to your code editor.
  7. Open photo-gallery.html from the same folder.
  8. Preview this page in your browser. You'll notice this page contains an identical accordion interface, but it's completely non-functional. This is because the JavaScript code exists only in the index.html file, highlighting the problem we're about to solve.

Setup Requirements

0/4

Externalizing JavaScript

Currently, our photo gallery page lacks the JavaScript functionality that powers the accordion. While copying and pasting the code might seem like a quick fix, this approach creates maintenance nightmares and violates the DRY (Don't Repeat Yourself) principle. Instead, we'll implement the professional solution: moving our JavaScript into an external file that both pages can reference. This approach ensures consistent functionality across pages while maintaining a single, authoritative codebase.

  1. Switch back to your code editor and open index.html.
  2. Locate the script tag around line 86.
  3. Carefully select all the JavaScript code between the opening and closing script tags. This is crucial: select only the JavaScript content, not the HTML script tags themselves.

    <script>
       document.getElementById('comingUpContent').style.display = 'none';

    Code Omitted To Save Space

    function showEventsWeek() {

    Code Omitted To Save Space

    }
       function showComingUp() {

    Code Omitted To Save Space

    }
       function showPastEvents() {

    Code Omitted To Save Space

    }
       function hidePanels() {

    Code Omitted To Save Space

    }
    </script>
  4. Cut this code using Ctrl+X (Windows) or Cmd+X (Mac).

  5. Create a new file in your editor.

  6. Paste the JavaScript code into this new file.

  7. Save the file as main.js in the js folder within the Sharing-JavaScript directory. This naming convention and folder structure follows industry standards for organizing web assets.

Important Code Selection

When cutting JavaScript code, select only the content between script tags, not the opening and closing script tags themselves. This prevents syntax errors in your external file.

Code Externalization Process

1

Locate Script Code

Find the script tag around line 86 in index.html containing accordion functionality

2

Extract JavaScript

Select and cut all code between script tags, excluding the tags themselves

3

Create External File

Create new file, paste code, and save as main.js in the js folder

Linking to the JavaScript File

Now that we've externalized our JavaScript code, we need to establish the connection between our HTML files and the new JavaScript file using the proper linking syntax.

  1. Return to index.html in your editor.
  2. Scroll to line 86 where you'll find the now-empty script tags.
  3. Modify the script tag to reference our external file. Remove any whitespace between the tags and add the src attribute:

    <script src="js/main.js"></script>
  4. Save the file and preview it in your browser. Test the accordion functionality thoroughly—it should work exactly as before, demonstrating that external JavaScript files provide identical functionality to inline code.
  5. Switch back to your code editor and open photo-gallery.html.
  6. Add the same script reference just before the closing </body> tag. This placement ensures the HTML content loads before the JavaScript executes:

    </div>
    <script src="js/main.js"></script> 
    </body>
  7. Save and preview the photo gallery page in your browser. Test the accordion functionality—it should now work perfectly, proving that both pages are successfully sharing the same JavaScript codebase.

    NOTE: For reference, you can examine our completed implementation in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Sharing-JavaScript.

Edit the tags as shown below (make sure to delete any extra lines and spaces between the opening and closing script tags)
Proper syntax is crucial for successful JavaScript file linking

Script Tag Syntax Comparison

FeatureInline JavaScriptExternal JavaScript
Syntax<script>code here</script><script src="js/main.js"></script>
MaintenanceUpdate each pageUpdate one file
ReusabilityCopy/paste requiredAutomatic sharing
Recommended: Always use external JavaScript files for production applications

External JavaScript: Professional Best Practices

Externalizing JavaScript isn't just a best practice—it's an industry standard that every professional developer should master. External JavaScript files improve page load performance through browser caching, enhance code maintainability, and enable better collaboration in team environments. Modern development workflows, build tools, and content delivery networks (CDNs) all assume external JavaScript architecture. While we'll continue using inline JavaScript in the next few exercises for instructional clarity, remember that production applications should always use external files for optimal performance and maintainability.

Course Structure Note

While external JavaScript is best practice for production, this course will continue using inline JavaScript for simplicity in upcoming exercises. External files will be revisited later in the curriculum.

External JavaScript Files

Pros
Code reusability across multiple pages
Easier maintenance and updates
Better browser caching performance
Cleaner HTML structure
Improved collaboration in team environments
Cons
Additional HTTP request for file loading
Slightly more complex initial setup
Requires proper file path management

Key Takeaways

1External JavaScript files enable code sharing across multiple web pages, eliminating the need for duplicate code
2Moving JavaScript from inline script tags to external .js files improves maintainability and reduces update complexity
3The script src attribute is used to link HTML pages to external JavaScript files using proper file paths
4When extracting JavaScript code, only select the content between script tags, not the tags themselves
5External JavaScript files should be saved in organized folder structures, typically in a js directory
6Testing functionality after externalization ensures the linking process was completed correctly
7External JavaScript is considered best practice for production websites due to performance and maintenance benefits
8Browser caching of external JavaScript files can significantly improve page load times for returning visitors

RELATED ARTICLES