The user wants an HTML5 boilerplate for a Single Page Application (SPA) that supports lazy loading of components.
Key requirements:
HTML5 Boilerplate: Standard structure (<!DOCTYPE html>, <html>, <head>, <body>).
SPA Architecture: Needs a way to handle routing or view switching without full page reloads.
Lazy Loading: Components (sections, logic, or assets) should load only when needed, not all at once at the initial load.
Implementation: Since the user asked for "HTML5 boilerplate," providing just HTML isn't enough to demonstrate lazy loading or SPA behavior. I need to include CSS and, crucially, JavaScript to handle the actual "SPA" and "Lazy Loading" mechanics.
Approach:
HTML Structure: A main container (e.g., <div id="app">) where views will be injected. Navigation links.
CSS: Basic styling to show the active view and hide others (or clear the container).
JavaScript (Vanilla JS): I should avoid heavy frameworks (React, Vue, Angular) unless asked, as "HTML5 boilerplate" usually implies a lighter, fundamental approach or a starting point for a custom solution. Using Vanilla JS keeps it universally understandable and dependency-free.
Router: A simple hash-based router (window.location.hash).
Lazy Loading Mechanism:
Option A: Dynamic Import (ES Modules). This is the modern, standard way. import('./component.js').
Option B: Fetch HTML. Fetching partial HTML files and injecting them.
Option C: Intersection Observer. Loading components when they scroll into view (less "SPA routing" and more "infinite scroll/performance").
Decision: For a generic SPA, dynamic routing based on hash changes coupled with dynamic script loading or template fetching is the best demonstration. I will go with Dynamic Import (ES Modules) because it's native to modern browsers and fits the "modern boilerplate" requirement perfectly.
Structure of the solution:
index.html: The entry point.
App Logic (in app.js): Handles routing and dynamic imports.
Component files (simulated): I'll create placeholders in the code comments or a separate block to show how the components would look.
Let's refine the "Lazy Loading" aspect.
Scenario: User clicks "About".
Action: Router detects change -> checks if "About" logic is loaded -> fetches about.js -> executes it -> updates DOM.
export default function render(container) {
container.innerHTML = '<h1>Home</h1>';
}
Wait, if I provide a single file solution, the user can't easily copy-paste file modules. However, the prompt asks for "HTML5 boilerplate". Usually, this means a single file or a folder structure. I should probably provide a single-file version using a small templating system or dynamic script injection if I can't assume a module bundler environment (like Vite/Webpack), but ES modules work natively in browsers now if served from a server.
To make it immediately runnable (even via file:// potentially, though modules usually need a local server), I should stick to the ES Module standard as it's the modern HTML5 way.
Let's package this as a file structure guide + code blocks.
Alternative interpretation: Lazy loading images/components within the view?
The prompt says "lazy loading of components" in an SPA. Usually, that refers to code splitting (Route-based splitting).
I will implement a Hash-Router that uses Dynamic Imports (import()). This is the standard "Vanilla SPA" approach today.
Refining the Boilerplate:
Meta tags: Viewport, charset, theme-color.
No-JS fallback: Helpful for robustness.
CSS: A simple "page" class and transitions.
JS: The Router.
Let's write the code mentally.
index.html
Standard stuff.
<div id="root"></div><script src="app.js" type="module"></script>
app.js
Router class.
load(routeName)
Check import('./routes/${routeName}.js')
Then call render() on that module.
The "Lazy" Part:
I need to emphasize that the code for the "About" page is not in the app.js bundle. It is in a separate file fetched only when the route is visited.
Self-Contained Example:
To be most helpful, I will provide:
The main index.html.
The logic for app.js (The Router).
Examples of what the lazy-loaded component files look like.
I will also add a fallback method using fetch for HTML partials in case they prefer HTML-only lazy loading (no build step required for logic, just html injection).
Actually, dynamic imports are cleaner. I'll stick to dynamic imports (ES Modules).
Structure of response:
Project Structure: Brief overview.
index.html: The main shell.
app.js: The core router logic using Dynamic Imports.
components/home.js: Example component.
Instructions: How to run (needs local server).
Let's add a bit of polish. A loading indicator.
When hashchange fires -> show "Loading..." in #app -> await import(...) -> replace content.
Is there a way to do this in one HTML file for easy testing?
Yes, by creating a mock module system or simply fetching HTML templates.
Fetching HTML templates is often easier for beginners than setting up a local server for ES modules.
However, "Modern Boilerplate" implies ES Modules.
I will provide the ES Module approach as the primary answer because it is the industry standard for "SPA Lazy Loading".
Final check on "Lazy Loading Components":
Does it mean specific UI elements (like a heavy chart) inside a page?
Or page-level components (Views)?
I will assume Route-based code splitting (SPA Views) as that is the definition of an SPA. I'll mention IntersectionObserver for elements as a secondary note.
Let's construct the response.
HTML: Semantic tags (header, nav, main, footer).
CSS: Clean layout, display: none vs removing nodes. Removing nodes is better for memory/performance in complex apps, but display: none keeps state? No, SPAs usually destroy the view to save DOM size. I'll destroy and recreate.
JS:
router.js (embedded in app.js for brevity).
Event listener for hashchange.
Dynamic import function.
I will use a standardized naming convention: views/[route].js.
One tricky part: Error handling. If the route doesn't exist, load a 404 view.
I will include a simple inline 404 view logic to keep it robust.
Let's assemble.
Here is a complete, modern HTML5 Single Page Application (SPA) boilerplate. It uses ES Modules (native JavaScript modules) to implement lazy loading without requiring complex build tools like Webpack or Vite (though it is compatible with them).
The Architecture
The Shell (index.html): Contains the navigation and the mount point (<main id="app">).
The Router (app.js): Listens for URL changes (hash changes) and dynamically import() the file associated with that view.
The Components: Separate .js files that export a render() function.
This is the core of the SPA. It uses dynamic imports (import(...)) to fetch JavaScript files only when the user navigates to them.
javascript
// Configuration: Map URL hashes to file paths
const routes = {
'/': './views/home.js',
'/about': './views/about.js',
'/contact': './views/contact.js'
};
const appContainer = document.getElementById('app');
// 1. The Router Function
async function router() {
// Remove the leading '#' from the hash
const hash = window.location.hash.slice(1) || '/';
// Default to home if route not found
const routePath = routes[hash] || routes['/'];
try {
// 2. Lazy Loading: Dynamic Import
// The browser fetches this file only when this line runs.
const module = await import(routePath);
// 3. Mount the Component
// We assume the module exports a default function called 'render'
if (module && typeof module.default === 'function') {
appContainer.innerHTML = module.default();
} else {
appContainer.innerHTML = '<h1>Error: Invalid Component</h1>';
}
} catch (error) {
console.error(error);
appContainer.innerHTML = '<h1>404 - Page Not Found</h1>';
}
}
// 4. Event Listeners
// Listen for hash changes in the URL
window.addEventListener('hashchange', router);
// Load the initial route when the page finishes loading
window.addEventListener('load', router);
views/home.js (A Lazy Component)
This file is not downloaded by the browser until the user clicks "Home" (or loads the initial page).
javascript
// You can include logic here, fetch data, etc.
export default () => {
return `
<div class="view">
<h1>Welcome Home</h1>
<p>This component was loaded lazily via <code>./views/home.js</code>.</p>
<p>Check your Network tab in DevTools to see the file load when you navigate!</p>
</div>
`;
};
views/about.js (Another Lazy Component)
javascript
export default () => {
return `
<div class="view">
<h1>About Us</h1>
<p>This is a separate JavaScript file.</p>
<p>If you never click this link, your browser never downloads this file, saving bandwidth.</p>
</div>
`;
};
views/contact.js (Complex Component Example)
This example shows how to include logic inside a component.
javascript
export default () => {
const currentYear = new Date().getFullYear();
// Note: Event listeners for elements inside this HTML string
// should be attached after injection, or use delegation on 'appContainer'.
return `
<div class="view">
<h1>Contact</h1>
<p>Email us at: example@domain.com</p>
<p>Copyright year generated dynamically: ${currentYear}</p>
</div>
`;
};
How to Run This
Because this uses ES Modules, you cannot simply open index.html directly from the file system (CORS security errors will occur). You must serve it via a local web server.
Using VS Code: Install the "Live Server" extension, right-click index.html, and choose "Open with Live Server".
Using Python: Run python -m http.server in the folder.
Using Node.js: Run npx serve in the folder.
Key Features of this Boilerplate
No Build Step: It works natively in all modern browsers without Babel, Webpack, or Vite.
Code Splitting: The import() syntax ensures the user only downloads the code for the page they are currently viewing.
Separation of Concerns: View logic is split into separate files inside the /views folder.