veza/apps/web/src/hooks/usePreload.ts
2025-12-12 21:34:34 -05:00

78 lines
1.9 KiB
TypeScript

import { useEffect } from 'react';
interface PreloadOptions {
images?: string[];
scripts?: string[];
styles?: string[];
prefetch?: string[];
}
export function usePreload(options: PreloadOptions) {
useEffect(() => {
const { images = [], scripts = [], styles = [], prefetch = [] } = options;
// Preload images
images.forEach((src) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = src;
document.head.appendChild(link);
});
// Preload scripts
scripts.forEach((src) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'script';
link.href = src;
document.head.appendChild(link);
});
// Preload styles
styles.forEach((href) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'style';
link.href = href;
document.head.appendChild(link);
});
// Prefetch resources
prefetch.forEach((href) => {
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = href;
document.head.appendChild(link);
});
// Cleanup function
return () => {
// Remove preload links on cleanup
const preloadLinks = document.querySelectorAll(
'link[rel="preload"], link[rel="prefetch"]',
);
preloadLinks.forEach((link) => {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
});
};
}, [options]);
}
// Hook pour preloader les routes
export function usePreloadRoute(routePath: string) {
useEffect(() => {
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = routePath;
document.head.appendChild(link);
return () => {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
};
}, [routePath]);
}