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.
This tutorial demonstrates transforming embedded JavaScript into reusable external files, using a product color chooser that works across multiple webpage types.
Project Setup Requirements
Locate Project Files
Open the Sharing-JavaScript folder from Desktop > Class Files > JavaScript Class in your code editor
Examine Existing Pages
Review chair.html with working color chooser and wall-clock.html without JavaScript functionality
Identify Code Duplication
Recognize the need to share JavaScript functionality between multiple product pages
External JavaScript Files vs Inline Code
When extracting JavaScript code, copy only the content between script tags, not the opening and closing script tags themselves.
Script Tag Implementation Methods
| Feature | Inline JavaScript | External JavaScript |
|---|---|---|
| Code Location | Inside HTML file | Separate .js file |
| HTML Syntax | <script>code here</script> | <script src="path/file.js"></script> |
| Reusability | Single page only | Multiple pages |
| Maintenance | Update each page | Update one file |
productPhoto.src = 'img/ ' + productPhoto.className + ' -' + this.id + '.jpg';
Code Flexibility Implementation
Use element properties like className to make code adaptable
Verify that dynamic code works for chair.html and wall-clock.html
Ensure all product pages use the same class naming convention
Check that dynamic paths correctly reference image files
Key Takeaways
