veza/apps/web/src/hooks/usePreload.ts

79 lines
1.9 KiB
TypeScript
Raw Normal View History

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
2025-12-13 02:34:34 +00:00
images.forEach((src) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = src;
document.head.appendChild(link);
});
// Preload scripts
2025-12-13 02:34:34 +00:00
scripts.forEach((src) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'script';
link.href = src;
document.head.appendChild(link);
});
// Preload styles
2025-12-13 02:34:34 +00:00
styles.forEach((href) => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'style';
link.href = href;
document.head.appendChild(link);
});
// Prefetch resources
2025-12-13 02:34:34 +00:00
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(
2025-12-13 02:34:34 +00:00
'link[rel="preload"], link[rel="prefetch"]',
);
2025-12-13 02:34:34 +00:00
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]);
}