Optimized loading of large video on PC
Demand background
Render a 16 second 40M video on the front page?? I had to load it to the year of monkey. I came up with a plan to split the video resources. After the efforts of my professional friends, the video resources were finally divided into 4 videos, each of which was about 2M.
Technical solution
Break it into 4 short videos and play them sequentially to form a complete 16-second video
Implementation process:
- First test of the water (failed) :
Because we did not want to generate 4 videos, we used one video and dynamically changed SRC. However, at the moment of switching, a flash screen would appear due to the loading of new resources, and the code would not be pasted.
- Second test (successful) :
This section mainly solves the problem of flash screen. Also, 4 videos are selected to control visual continuity by controlling opacity of dom. Core idea: Monitor the completion of the ended playback of every video, and opacity:1 for the video in playback, while the rest are 0. Ps: After each video is played, the listener should be removed; otherwise, the listener will be monitored until the ended of that video
const { data: videoList } = props; const videos = useRef([]); const [count, setCount] = useState(0); const loop = () => { videoList.forEach((item, index) => { if (videos.current? .children) { videos.current.children[index].style.opacity = 0; videos.current.children[index].removeEventListener('ended', loop); }}); setCount((pre) => { let newCount = pre + 1; if (pre === 3) { newCount = 0; } play(newCount); return newCount; }); }; const play = (c) => { videos.current.children[c].style.opacity = 1; videos.current.children[c].play(); videos.current.children[c].addEventListener('ended', loop); }; useEffect(() => { play(0); } []); return ( <div className={styles.box}> <div className={styles.banner} ref={videos}> {videoList.map((item, index) => { return ( <video muted preload="auto" src={item} key={index} data-count={count} /> ); })} </div> </div> ); };Copy the code