Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Code splitting is the practice of breaking your bundle into smaller chunks that can be loaded on demand. Instead of loading all JavaScript upfront, you load only what's needed for the current page.
Smaller initial bundle = faster page load
Users download only what they use
Improved performance = happier users
Split code by routes/pages
Lazy load large components
Separate third-party libraries
Load modules conditionally
// Load module dynamically
button.addEventListener('click', async () => {
// Module is loaded only when button is clicked
const module = await import('./heavy-feature.js');
module.initializeFeature();
});
// Conditional loading
async function loadEditor() {
if (userRole === 'admin') {
const { RichTextEditor } = await import('./editor.js');
const editor = new RichTextEditor();
editor.render();
}
}
// Load with error handling
async function loadChart(data) {
try {
const { Chart } = await import('./chart-library.js');
const chart = new Chart(data);
chart.display();
} catch (error) {
console.error('Failed to load chart:', error);
showFallbackView();
}
}
// Parallel loading
async function loadDashboard() {
const [
{ StatsWidget },
{ ChartWidget },
{ TableWidget }
] = await Promise.all([
import('./stats.js'),
import('./chart.js'),
import('./table.js')
]);
// All widgets loaded in parallel
new StatsWidget().render();
new ChartWidget().render();
new TableWidget().render();
}import React, { lazy, Suspense } from 'react';
// Lazy load components
const Dashboard = lazy(() => import('./Dashboard'));
const Profile = lazy(() => import('./Profile'));
const Settings = lazy(() => import('./Settings'));
// Heavy component loaded on demand
const ChartComponent = lazy(() => import('./HeavyChart'));
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
// Lazy load modal
function DataTable() {
const [showModal, setShowModal] = useState(false);
// Modal component loaded only when opened
const Modal = lazy(() => import('./DetailModal'));
return (
<div>
<button onClick={() => setShowModal(true)}>
View Details
</button>
{showModal && (
<Suspense fallback={<div>Loading...</div>}>
<Modal onClose={() => setShowModal(false)} />
</Suspense>
)}
</div>
);
}
// Named export lazy loading
const AdminPanel = lazy(() =>
import('./AdminPanel').then(module => ({
default: module.AdminPanel
}))
);// webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
},
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
// Separate vendor code
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: 10
},
// Common code shared between routes
common: {
minChunks: 2,
priority: 5,
reuseExistingChunk: true
},
// Separate large libraries
react: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'react',
priority: 20
},
lodash: {
test: /[\\/]node_modules[\\/]lodash[\\/]/,
name: 'lodash',
priority: 15
}
}
},
// Separate runtime chunk
runtimeChunk: 'single'
}
};
// Vite configuration
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
'react-vendor': ['react', 'react-dom'],
'ui-library': ['@mui/material', '@mui/icons-material'],
'utils': ['lodash', 'moment', 'axios']
}
}
}
}
};import dynamic from 'next/dynamic';
// Basic dynamic import
const DynamicComponent = dynamic(() => import('./HeavyComponent'));
// With custom loading component
const Chart = dynamic(() => import('./Chart'), {
loading: () => <p>Loading chart...</p>,
ssr: false // Disable server-side rendering
});
// With named exports
const AdminPanel = dynamic(() =>
import('./AdminPanel').then(mod => mod.AdminPanel)
);
// Conditional loading
function Dashboard({ user }) {
const AdminDashboard = dynamic(() => import('./AdminDashboard'));
const UserDashboard = dynamic(() => import('./UserDashboard'));
return user.isAdmin ? <AdminDashboard /> : <UserDashboard />;
}
// Multiple components
const [
Header,
Footer,
Sidebar
] = [
dynamic(() => import('./Header')),
dynamic(() => import('./Footer')),
dynamic(() => import('./Sidebar'))
];
// Load only on client side
const NoSSRComponent = dynamic(
() => import('./ClientOnlyComponent'),
{ ssr: false }
);Route-based splitting is easiest
Most effective optimization
Charts, editors, modals
Load on demand
Show loading states
Better user experience
Use bundle analyzers
Track size over time