react-lazy-monolith
v1.1.0
Published
A React library that extends React.lazy() with preloading and monolith mode capabilities.
Readme
react-lazy
A React library that extends React.lazy() with preloading and monolith mode capabilities.
Features
- Preloading: Load components ahead of time before they're rendered
- Monolith Mode: Automatic fallback to monolith mode on load errors
- Error Recovery: Automatic page reload attempt on first load failure
- Shared Caching: Preloaded components are cached and reused across instances
Installation
npm install react-lazyUsage
Example 1: Basic Preload
Preload components to improve perceived performance:
import { lazyWithPreload } from 'react-lazy';
import LoadingSpinner from './LoadingSpinner';
const MyComponent = lazyWithPreload(
() => import('./MyComponent'),
{
key: 'MyComponent',
Fallback: LoadingSpinner,
onError: (error, key) => {
console.error(`Failed to load ${key}:`, error);
},
}
);
// Preload when user hovers over a link
function NavigationLink() {
const handleMouseEnter = () => {
MyComponent.preload();
};
return (
<a href="/my-page" onMouseEnter={handleMouseEnter}>
Go to My Page
</a>
);
}
function App() {
return <MyComponent />;
}Example 2: Monolith Mode
When lazy-loaded components fail to load, the library automatically enables monolith mode. Add this script to your index.html to load the monolith bundle when enabled:
<script>
(function () {
const monolithEnabled =
sessionStorage.getItem('monolith-enabled') === 'true';
if (!monolithEnabled) {
return;
}
console.log('Monolith enabled');
var s = document.createElement('script');
s.src = '/assets/index.js?v=' + Date.now(); // optional cache-bust
s.type = 'module';
s.async = true;
s.onerror = function () {
console.error('Monolith failed to load');
};
document.head.appendChild(s);
})();
</script>API
lazyWithPreload<T>(factory, options)
Creates a lazy-loaded component with preloading support.
Parameters
factory:() => Promise<{ default: T }>- Function that returns a promise resolving to a module with a default exportoptions:key:string- Unique identifier for this lazy component (used for caching)Fallback:ComponentType<any>- Component to render while loading or on erroronError:(error: unknown, key: string) => void- Callback invoked when component fails to loadonMonolithEnabled?:(key: string) => void- Optional callback when monolith mode is enabled
Returns
A component with a .preload() method that can be called to preload the component.
License
MIT
