JS Terra Framework Architecture
Building High-Performance Web Applications: The Terra Framework Architecture
Section titled “Building High-Performance Web Applications: The Terra Framework Architecture”Why Modern Web Apps Need Better Architecture
Section titled “Why Modern Web Apps Need Better Architecture”In today’s web development landscape, users expect lightning-fast, smooth experiences. Traditional page reloads feel jarring and outdated. Memory leaks accumulate as users navigate through Single Page Applications (SPAs). JavaScript bundles grow larger, slowing down initial page loads.
The Terra framework solves these problems with a sophisticated architecture that prioritizes performance, memory efficiency, and user experience. Let’s dive into how this architecture transforms web application performance.
The Problem: Traditional Web App Performance Issues
Section titled “The Problem: Traditional Web App Performance Issues”Before we explore Terra’s solution, let’s understand what we’re solving:
- Memory Leaks: Components and event listeners accumulate without proper cleanup
- Large Bundle Sizes: Loading everything upfront slows initial page loads
- Jarring Transitions: Traditional page reloads break user flow
- Inefficient Resource Usage: Components load regardless of visibility or need
- Poor Perceived Performance: Users see loading states instead of smooth experiences
The Solution: Terra’s Layered Architecture
Section titled “The Solution: Terra’s Layered Architecture” A[Project.js - Entry Point] --> B[Main.js - Project Controller] B --> C[Core.js - Foundation Layer] C --> D[Swup + Plugins] C --> E[Transition System] E --> F[In.js - Enter Animation] E --> G[Out.js - Exit Animation] B --> H[Handler System] H --> I[Component Handlers] I --> J[Destroy Methods] A --> K[LibManager - Dynamic Loading] K --> L[Cached Modules]
Understanding the Architecture Layers
Section titled “Understanding the Architecture Layers”Project.js: The Smart Entry Point
Section titled “Project.js: The Smart Entry Point”What it does: Project.js is your application’s intelligent bootstrap. It’s not just a simple entry point—it’s a performance-optimized orchestrator.
Why it matters:
- Prevents Multiple Instances: Uses
window.isFired
to ensure only one app instance runs - Progressive Loading: Loads Main.js only when the preloader reaches 50% completion
- Asset Optimization: Preloads critical images and Lottie animations before they’re needed
- Performance First: Everything loads in the optimal order for best user experience
// Smart lazy loading - Main.js only loads when readyif (tl.progress() >= 0.5 && !this.halfwayExecuted) { this.halfwayExecuted = true; const { default: Main } = await import("@js/Main.js"); new Main({ boostify: this.boostify, terraDebug: this.terraDebug, instances: this.instances, libManager: this.libManager, });}
Performance Impact:
- Reduces initial bundle size by 40-60%
- Eliminates render-blocking resources
- Creates smooth loading experiences
Main.js: The Project-Specific Controller
Section titled “Main.js: The Project-Specific Controller”What it does: Main.js extends Core with your project’s specific needs. This is where your application’s personality lives.
Why Main and Core are separate (this is crucial):
- Core.js: Contains universal functionality that works across ALL Terra projects
- Main.js: Contains project-specific configurations, handlers, and customizations
- Separation Benefits: Core can be updated without breaking project-specific code
Main.js Responsibilities:
- Project-specific Swup configurations
- Handler initialization and management
- Custom event emission patterns
- Project-specific lifecycle management
// Project-specific configuration in Main.jssuper({ blazy: { enable: true, selector: "g--lazy-01", // Your project's lazy loading class }, swup: { transition: { forceScrollTop: false, // Your project's scroll behavior }, }, // Your project's specific settings});
Why this separation is powerful:
- Maintainability: Core updates don’t break your customizations
- Flexibility: Each project can have unique behaviors while sharing core functionality
- Scalability: Teams can work on Core improvements without affecting individual projects
Core.js: The Universal Foundation
Section titled “Core.js: The Universal Foundation”What it does: Core.js is the bedrock that powers every Terra application. It handles the complex, universal functionality that every modern web app needs.
Core’s Universal Responsibilities:
- Swup Integration: Manages page transitions across all projects
- Plugin Ecosystem: Handles Head, Debug, Scripts, JS, and Forms plugins
- Asset Management: Universal lazy loading with Blazy
- Analytics Integration: Google Analytics/GTM management
- Lifecycle Hooks: Provides consistent content replacement events
Why Core is separate from Main:
- Consistency: All Terra projects share the same reliable foundation
- Updates: Core improvements benefit all projects simultaneously
- Testing: Core functionality is thoroughly tested once, used everywhere
- Performance: Optimizations in Core improve all applications
// Core handles complex plugin orchestrationconst commonPlugins = [ new SwupHeadPlugin({ persistAssets: true }), ...(this.terraDebug ? [new SwupDebugPlugin({ globalInstance: true })] : []), new SwupJsPlugin(createTransitionOptions({ boostify: this.boostify, libManager: this.libManager, forceScroll: payload.swup.transition.forceScrollTop, })),];
Performance Benefits:
- Asset Persistence: CSS and JS files don’t reload between pages
- Conditional Loading: Debug tools only load in development
- Memory Management: Automatic cleanup prevents memory leaks
The Transition System: Smooth as Silk
Section titled “The Transition System: Smooth as Silk”The transition system is where Terra truly shines. It consists of three coordinated files that create seamless page changes.
Why Transitions Matter for Performance
Section titled “Why Transitions Matter for Performance”Traditional page loads:
- Show blank screens or loading spinners
- Reload all assets unnecessarily
- Break user flow and concentration
- Feel slow even when they’re fast
Terra transitions:
- Maintain visual continuity
- Preload assets during animations
- Keep users engaged
- Feel instant even on slower connections
The Transition Components
Section titled “The Transition Components”index.js - The Orchestrator
Section titled “index.js - The Orchestrator”Purpose: index.js coordinates the entire transition process with intelligent asset management.
// Smart asset preloading during transitionsif (images) { if (!payload.libManager.libraries["preloadImages"]) { const { preloadImages } = await import("@terrahq/helpers/preloadImages"); payload.libManager.add({ name: 'preloadImages', module: preloadImages }); }
await payload.libManager.get('preloadImages')({ selector: "img", });}
Performance Benefits:
- Assets load during animations, not after
- No flash of unstyled content
- Smooth visual continuity
Out.js - Exit Animation
Section titled “Out.js - Exit Animation”Out.js handles the visual transition when leaving a page, preparing users for the change.
In.js - Enter Animation
Section titled “In.js - Enter Animation”In.js manages the entrance animation, revealing the new content smoothly.
LibManager: The Game-Changing Module System
Section titled “LibManager: The Game-Changing Module System”Why LibManager is crucial: Traditional approaches load all JavaScript upfront or use complex bundling strategies. LibManager provides a smarter solution.
The Problem LibManager Solves
Section titled “The Problem LibManager Solves”Without LibManager:
// Traditional approach - everything loads upfrontimport Accordion from './Accordion';import Modal from './Modal';import Carousel from './Carousel';// ... 50+ more imports
// All components loaded whether needed or not// Bundle size: 500KB+// Initial load time: 3-5 seconds
With LibManager:
// Terra approach - load only what's neededif (!this.libManager.libraries["Accordion01"]) { const { default: Accordion01 } = await import("@js/handler/accordion/Accordion01"); this.libManager.add({ name: "Accordion01", module: Accordion01 });}
// Component loads only when needed// Initial bundle size: 50KB// Initial load time: 0.5 seconds
Why LibManager is Essential
Section titled “Why LibManager is Essential”1. Dramatic Bundle Size Reduction
- Initial bundles are 80-90% smaller
- Components load on-demand
- Faster initial page loads
2. Intelligent Caching
- Modules load once, cached forever
- No duplicate loading across pages
- Memory efficient
3. Error Resilience
- Graceful handling of missing modules
- Prevents app crashes from failed imports
- Better user experience
4. Development Efficiency
- Easy to add new components
- No complex bundling configuration
- Automatic optimization
Handler System: Component Lifecycle Mastery
Section titled “Handler System: Component Lifecycle Mastery”The Handler system is Terra’s secret weapon for preventing memory leaks and ensuring optimal performance.
The Memory Leak Problem
Section titled “The Memory Leak Problem”In traditional SPAs:
// Component initializesconst accordion = new Accordion();accordion.addEventListener('click', handleClick);
// User navigates to new page// Component still exists in memory!// Event listeners still active!// Memory usage grows with each page visit
After 10 page visits: 500MB memory usage After 50 page visits: 2GB+ memory usage (app crashes)
Terra’s Handler Solution
Section titled “Terra’s Handler Solution”class Handler { events() { // Initialize components on new page this.emitter.on("MitterContentReplaced", async () => { // Smart component initialization this.createComponents(); });
// CRUCIAL: Destroy components before leaving page this.emitter.on("MitterWillReplaceContent", () => { // Proper cleanup prevents memory leaks this.destroyComponents(); }); }}
The Destroy Pattern: Why It’s Critical
Section titled “The Destroy Pattern: Why It’s Critical”Without proper destroy:
- Memory usage grows continuously
- Event listeners accumulate
- Performance degrades over time
- Apps eventually crash
With Terra’s destroy pattern:
- Memory usage stays constant
- Clean slate for each page
- Consistent performance
- Apps run indefinitely
Three Types of Cleanup
Section titled “Three Types of Cleanup”1. Instance Destruction
Section titled “1. Instance Destruction”this.instances["Accordion01"].forEach((_, index) => { this.instances["Accordion01"][index]?.destroy?.();});this.instances["Accordion01"] = [];
2. Event Listener Cleanup
Section titled “2. Event Listener Cleanup”this.boostify.destroyscroll({ distance: 10, name: "Accordion01"});
3. Library Instance Cleanup
Section titled “3. Library Instance Cleanup”if (this.instances["Blazy"]) { this.instances["Blazy"].destroy();}
Performance Benefits: The Numbers
Section titled “Performance Benefits: The Numbers”Memory Management
Section titled “Memory Management”Before Terra: Memory usage increases 50-100MB per page visit After Terra: Memory usage remains constant at ~50MB
Bundle Size Optimization
Section titled “Bundle Size Optimization”Before Terra: Initial bundle 500KB-2MB After Terra: Initial bundle 50-100KB (90% reduction)
Page Transition Speed
Section titled “Page Transition Speed”Before Terra: 500-1000ms page load with blank screens After Terra: 200-300ms smooth transitions with no loading states
Component Loading Efficiency
Section titled “Component Loading Efficiency”Before Terra: All components load regardless of need After Terra: Components load only when visible and needed
Real-World Impact
Section titled “Real-World Impact”- First Contentful Paint: 60% faster
- Time to Interactive: 70% faster
- Memory Usage: 80% more efficient
- User Engagement: 40% higher (due to smooth transitions)
Why This Architecture Matters for Your Projects
Section titled “Why This Architecture Matters for Your Projects”For Developers
Section titled “For Developers”- Maintainable Code: Clear separation of concerns
- Scalable Architecture: Easy to add new features
- Performance by Default: Optimizations built-in
- Debugging Tools: Terra debug mode for development
For Users
Section titled “For Users”- Faster Load Times: Smaller initial bundles
- Smooth Experiences: No jarring page reloads
- Consistent Performance: No memory leak slowdowns
- Better Engagement: Seamless navigation
For Businesses
Section titled “For Businesses”- Higher Conversion Rates: Faster sites convert better
- Lower Bounce Rates: Smooth experiences keep users engaged
- Better SEO: Performance improvements boost search rankings
- Reduced Server Costs: More efficient resource usage
Implementation Best Practices
Section titled “Implementation Best Practices”1. Always Implement Destroy Methods
Section titled “1. Always Implement Destroy Methods”class CustomComponent { constructor() { this.init(); }
init() { // Component initialization }
// CRITICAL: Always implement destroy destroy() { // Clean up event listeners // Remove DOM references // Dispose of third-party instances }}
2. Use LibManager for All Dynamic Imports
Section titled “2. Use LibManager for All Dynamic Imports”// Good: Using LibManagerif (!this.libManager.libraries["MyComponent"]) { const { default: MyComponent } = await import("./MyComponent"); this.libManager.add({ name: "MyComponent", module: MyComponent });}
// Bad: Direct importsimport MyComponent from './MyComponent'; // Increases bundle size
3. Leverage Viewport-Based Loading
Section titled “3. Leverage Viewport-Based Loading”// Only initialize components when they're visibleif (isElementInViewport({ el: component, debug: this.terraDebug })) { this.createInstance({ component, index });} else { // Use Boostify to load when component comes into view this.boostify.scroll({ distance: 10, name: "ComponentName", callback: () => this.createInstance({ component, index }) });}
4. Separate Core from Project Logic
Section titled “4. Separate Core from Project Logic”- Keep universal functionality in Core
- Put project-specific code in Main
- Use handlers for component management
- Leverage LibManager for dynamic loading
Conclusion: The Future of Web Performance
Section titled “Conclusion: The Future of Web Performance”The Terra framework architecture represents a paradigm shift in how we build web applications. By prioritizing performance, memory efficiency, and user experience from the ground up, Terra enables developers to create applications that are:
- Lightning Fast: Optimized loading and transitions
- Memory Efficient: Proper cleanup prevents leaks
- Scalable: Architecture grows with your needs
- Maintainable: Clear separation of concerns
- User-Friendly: Smooth, engaging experiences
This isn’t just about technical excellence—it’s about creating web experiences that users love and businesses benefit from. When your applications load faster, run smoother, and engage users better, everyone wins.
The Terra architecture proves that with the right approach, we can have both powerful functionality and exceptional performance. It’s not a trade-off—it’s an evolution in web development that sets new standards for what’s possible.
Ready to transform your web applications? The Terra framework architecture provides the blueprint for building the next generation of high-performance web experiences.