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.
What We'll Accomplish
Identify the Problem
Recognize that accordion functionality works on index.html but not on photo-gallery.html due to missing JavaScript
Extract JavaScript
Move JavaScript code from HTML into a separate .js file for reusability
Link External File
Connect both HTML pages to the shared JavaScript file using script src attributes
Setup Requirements
Start with a clean workspace to avoid confusion
Located in Desktop > Class Files > yourname-JavaScript jQuery Class
Verify the working implementation before making changes
Understand the problem we're solving
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
Locate Script Code
Find the script tag around line 86 in index.html containing accordion functionality
Extract JavaScript
Select and cut all code between script tags, excluding the tags themselves
Create External File
Create new file, paste code, and save as main.js in the js folder
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
Key Takeaways
