SPA (Single Page Application) is a web application that loads a single HTML page and dynamically updates content without page reloads:
// Simple SPA router example
const routes = {
'/': () => showHome(),
'/about': () => showAbout(),
'/contact': () => showContact()
};
function navigate(path) {
history.pushState(null, null, path);
routes[path]();
}SPA is like a desktop application in the browser! Instead of loading new pages, the application dynamically changes the content of a single page. 🖥️
// Traditional application
window.location.href = '/new-page'; // Page reload
// SPA application
history.pushState({}, '', '/new-page'); // No reload
updateContent(); // Content updateMain components of SPA application:
// Router
class Router {
constructor() {
this.routes = {};
window.addEventListener('popstate', this.handleRoute.bind(this));
}
addRoute(path, handler) {
this.routes[path] = handler;
}
navigate(path) {
history.pushState({}, '', path);
this.handleRoute();
}
}
// Components
class Component {
render() {
return '<div>Component content</div>';
}
}Navigation without page reloads:
// React Router example
import { BrowserRouter, Route, Switch } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</BrowserRouter>
);
}Data stored in browser memory:
// Simple state
const state = {
user: null,
posts: [],
currentPage: 'home'
};
// Redux example
const store = createStore(reducer);
function updateUser(user) {
store.dispatch({ type: 'SET_USER', payload: user });
}Loading data without page reloads:
// Fetch API
async function loadData() {
const response = await fetch('/api/data');
const data = await response.json();
updateUI(data);
}
// Axios example
axios.get('/api/users')
.then(response => {
setUsers(response.data);
});function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}<template>
<div>
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
export default {
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
}
}
};
</script>@Component({
selector: 'app-counter',
template: `
<h1>Count: {{ count }}</h1>
<button (click)="increment()">Increment</button>
`
})
export class CounterComponent {
count = 0;
increment() {
this.count++;
}
}// Fast navigation
function showPage(pageId) {
// Hide all pages
document.querySelectorAll('.page').forEach(page => {
page.style.display = 'none';
});
// Show needed page
document.getElementById(pageId).style.display = 'block';
}// Lazy loading components
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}// Next.js example
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}// Preload critical resources
const link = document.createElement('link');
link.rel = 'preload';
link.href = '/critical-component.js';
link.as = 'script';
document.head.appendChild(link);| SPA | MPA |
|---|---|
| Single HTML page | Multiple HTML pages |
| Client-side routing | Server-side routing |
| Fast navigation | Page reloads |
| Complex SEO | Simple SEO |
| Large initial bundle | Small pages |
✅ Good for:
❌ Not good for:
// Error handling
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Network error');
return await response.json();
} catch (error) {
showErrorMessage('Failed to load data');
return null;
}
}// Service Worker for offline work
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});// Modular architecture
const HeaderApp = () => import('./header-app');
const MainApp = () => import('./main-app');
const FooterApp = () => import('./footer-app');SPA is a powerful architecture for creating interactive web applications:
Choose SPA for interactive applications with frequent navigation! 🎯