Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Write HTML5 boilerplate for a single-page app (SPA) that supports lazy loading of…

  1. User

    Write HTML5 boilerplate for a single-page app (SPA) that supports lazy loading of components.

  2. Gemini Assistant

    Developing the SPA Framework

    I'm focusing now on understanding the user's ultimate goal: a tailored HTML5 boilerplate for a Single Page Application. I've been drilling down into the specific needs and features a SPA demands, particularly around routing and component management. I'm starting to think about what the base structure of such a project might look like.

    Refining the Approach

    I'm now fully immersed in the nitty-gritty of lazy loading. My focus has narrowed to a no-build-tool scenario, opting for a Vanilla JS solution that uses native ES Modules for simplicity. This approach will illustrate the mechanics of component loading. It will be helpful to show the user the core elements, like the use of dynamic imports to load only necessary components.

    Crafting the Foundation

    I'm presently building the essential HTML structure, focusing on essential tags and a basic layout. My attention is now on the CSS for a simple, visually appealing experience, alongside a vital loading spinner to clearly illustrate the lazy-loading functionality. The critical focus is on the JavaScript logic, specifically designing the router. I am also working on defining routes that correspond to modules and implementing robust error handling.

    Conceptualizing the Implementation

    I'm presently simulating the component loading, since I can't provide several files in one chunk. My focus is now the boilerplate. This calls for real syntax, I'm thinking I'll add the necessary HTML and some comments. I'll describe the required files and the router function. It will demonstrate how to structure the navigation and use modulepreload hints for optimization.

    Constructing the Demo

    I'm now fully immersed in the core structure. My latest focus is on the HTML for navigation, including links for "Home" and "Settings," which will drive the SPA. In my Javascript I am creating an event listener that handles link clicks, preventing a default refresh, and implements the router. Next, I'll be adding "mock" components to illustrate lazy-loading. Finally, I'll be polishing everything.

    Implementing Route-Based Loading

    I'm now zeroing in on route-based lazy loading. The core of the design centers around efficiently loading routes/views as the user navigates the SPA. I'm prioritizing clarity, showing how the framework handles navigation and corresponding component loading. I'll showcase how module loading is tied directly to the user's interaction.

    Here is a robust, modern HTML5 boilerplate designed for a Vanilla JavaScript SPA that utilizes native ES Modules to handle lazy loading.

    This approach does not require a build tool (like Webpack or Vite) to understand the concepts, but it mimics the architecture used by frameworks. It uses Dynamic Imports (import()) to load components only when the specific route is requested.

    The File Structure

    To make this work, you would organize your project like this:

    /project-root
      ├── index.html
      └── src/
          ├── router.js
          └── pages/
              ├── Home.js
              └── Settings.js
    

    1. The Boilerplate (index.html)

    This file sets up the root element, the navigation interceptors, and the initial styling.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="A Lazy Loading SPA Boilerplate">
        <title>Lazy Load SPA</title>
        
        <style>
            /* Basic Reset */
            body, html { margin: 0; padding: 0; font-family: system-ui, sans-serif; }
            
            /* Layout */
            nav { background: #333; padding: 1rem; }
            nav a { color: white; text-decoration: none; margin-right: 1rem; }
            nav a:hover { text-decoration: underline; }
            
            main { padding: 2rem; }
    
            /* Loading Spinner Styles */
            .loader {
                border: 4px solid #f3f3f3;
                border-top: 4px solid #3498db;
                border-radius: 50%;
                width: 30px;
                height: 30px;
                animation: spin 1s linear infinite;
                display: none; /* Hidden by default */
            }
    
            .loader.active { display: block; }
    
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    </head>
    <body>
    
        <nav>
            <!-- data-link attribute is used to hijack click events in JS -->
            <a href="/" data-link>Home</a>
            <a href="/settings" data-link>Settings (Lazy)</a>
        </nav>
    
        <div class="loader" id="loader"></div>
        
        <!-- The Root Container -->
        <main id="app"></main>
    
        <!-- Main Entry Point -->
        <script type="module">
            import { router } from './src/router.js';
    
            // 1. Handle navigation (Back/Forward browser buttons)
            window.addEventListener("popstate", router);
    
            // 2. Handle Initial Load
            document.addEventListener("DOMContentLoaded", () => {
                document.body.addEventListener("click", e => {
                    if (e.target.matches("[data-link]")) {
                        e.preventDefault();
                        navigateTo(e.target.href);
                    }
                });
                router();
            });
    
            // Helper to push history state and run router
            const navigateTo = url => {
                history.pushState(null, null, url);
                router();
            };
        </script>
    </body>
    </html>
    

    2. The Logic (src/router.js)

    This script handles the routing and the specific Lazy Loading logic using await import(...).

    // src/router.js
    
    const app = document.getElementById('app');
    const loader = document.getElementById('loader');
    
    // Route definitions mapping paths to Dynamic Imports
    const routes = {
        "/": () => import('./pages/Home.js'),
        "/settings": () => import('./pages/Settings.js')
    };
    
    export const router = async () => {
        // 1. Show Loader
        loader.classList.add('active');
        app.innerHTML = '';
    
        // 2. Get current path
        const path = location.pathname;
        
        // 3. Match route or default to Home (simple implementation)
        // Note: In production, you'd handle 404s here.
        const loadRoute = routes[path] || routes["/"];
    
        try {
            // 4. LAZY LOAD: This pulls the file over the network only now
            const module = await loadRoute();
            
            // 5. Render the content provided by the module
            app.innerHTML = module.default.render();
            
            // Optional: Initialize any JS specific to that page
            if (module.default.afterRender) await module.default.afterRender();
    
        } catch (error) {
            console.error("Failed to load page", error);
            app.innerHTML = "<h1>Error loading page.</h1>";
        } finally {
            // 6. Hide Loader
            loader.classList.remove('active');
        }
    };
    

    3. The Hidden Components (src/pages/*.js)

    These files are not loaded when the user first opens the website. They are only downloaded when the user clicks the navigation links.

    src/pages/Home.js

    export default {
        render: () => {
            return `
                <h1>Home Page</h1>
                <p>This was loaded instantly because it is the default.</p>
            `;
        }
    };
    

    src/pages/Settings.js

    export default {
        render: () => {
            return `
                <h1>Settings Page</h1>
                <p>This content was <strong>Lazy Loaded</strong>!</p>
                <p>Check your Network tab in DevTools; Settings.js was only requested when you clicked the link.</p>
                <button id="alert-btn">Test Button</button>
            `;
        },
        // Example of creating interactivity after HTML injection
        afterRender: () => {
            document.getElementById('alert-btn').addEventListener('click', () => {
                alert('Javascript for this lazy component is working!');
            });
        }
    };
    

    How to Run This

    Because this uses ES Modules (type="module"), you cannot simply double-click the index.html file. Browsers block module requests from the filesystem (file://) for security (CORS).

    1. Install a simple server (if you have Node.js):
      npm install -g http-server
      
    2. Run the command in the folder:
      http-server .
      
    3. Open your browser (usually http://127.0.0.1:8080).
    4. Open DevTools > Network Tab.
    5. Clear the network log.
    6. Click "Settings". You will see Settings.js appear in the network tab only at that exact moment.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.