From a87b97e742db9f44a76a4a33c8d2bce87f058086 Mon Sep 17 00:00:00 2001 From: Khoa Vo Date: Sat, 20 Dec 2025 15:17:50 +0700 Subject: [PATCH] feat: smart video prefetching - buffer first 3 videos immediately on load --- frontend/src/components/Feed.tsx | 3 +++ frontend/src/utils/videoPrefetch.ts | 31 +++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/Feed.tsx b/frontend/src/components/Feed.tsx index bcb81a5..b421498 100644 --- a/frontend/src/components/Feed.tsx +++ b/frontend/src/components/Feed.tsx @@ -332,6 +332,9 @@ export const Feed: React.FC = () => { if (loaded.length > 0) { setVideos(loaded); setViewState('feed'); + + // Start prefetching first 3 videos immediately + videoPrefetcher.prefetchInitialBatch(loaded, 3); } } ); diff --git a/frontend/src/utils/videoPrefetch.ts b/frontend/src/utils/videoPrefetch.ts index 57994f9..b88504b 100644 --- a/frontend/src/utils/videoPrefetch.ts +++ b/frontend/src/utils/videoPrefetch.ts @@ -8,8 +8,8 @@ interface PrefetchConfig { } const DEFAULT_CONFIG: PrefetchConfig = { - lookahead: 2, - concurrency: 1, + lookahead: 3, // Increased from 2 for better buffering + concurrency: 2, // Increased from 1 for parallel downloads timeoutMs: 30000 }; @@ -49,6 +49,33 @@ class VideoPrefetcher { } } + /** + * Prefetch initial batch of videos immediately after feed loads. + * This ensures first few videos are ready before user starts scrolling. + */ + async prefetchInitialBatch( + videos: Video[], + count: number = 3 + ): Promise { + if (!this.isInitialized) await this.init(); + if (videos.length === 0) return; + + console.log(`PREFETCH: Starting initial batch of ${Math.min(count, videos.length)} videos...`); + + const toPrefetch = videos + .slice(0, count) + .filter((v) => v.url && !this.prefetchQueue.has(v.id)); + + // Start all prefetches in parallel (respects concurrency via browser limits) + const promises = toPrefetch.map((video) => { + this.prefetchQueue.add(video.id); + return this.prefetchVideo(video); + }); + + await Promise.allSettled(promises); + console.log(`PREFETCH: Initial batch complete (${toPrefetch.length} videos buffered)`); + } + private async prefetchVideo(video: Video): Promise { if (!video.url) return;