File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 8888 </ div >
8989
9090 < script >
91- document . querySelectorAll ( "video" ) . forEach ( ( video ) => {
92- const observer = new IntersectionObserver (
93- ( entries ) => {
94- entries . forEach ( ( entry ) => {
95- if ( entry . isIntersecting ) {
96- video . play ( ) ;
97- } else {
98- video . pause ( ) ;
99- }
100- } ) ;
101- } ,
102- { threshold : 0.25 }
103- ) ;
91+ const videos = document . querySelectorAll ( "video.autoplay-on-visible" ) ;
92+ const playDelays = new Map ( ) ; // To track timeouts per video
93+
94+ const playVideoSafely = ( video ) => {
95+ if ( video . readyState >= 2 ) {
96+ video . play ( ) . catch ( ( err ) => {
97+ console . warn ( "Video play failed:" , err ) ;
98+ } ) ;
99+ } else {
100+ setTimeout ( ( ) => playVideoSafely ( video ) , 100 ) ;
101+ }
102+ } ;
103+
104+ const observer = new IntersectionObserver (
105+ ( entries ) => {
106+ entries . forEach ( ( entry ) => {
107+ const video = entry . target ;
108+ clearTimeout ( playDelays . get ( video ) ) ;
109+
110+ if ( entry . isIntersecting ) {
111+ const timeout = setTimeout ( ( ) => {
112+ playVideoSafely ( video ) ;
113+ } , 100 ) ;
114+ playDelays . set ( video , timeout ) ;
115+ } else {
116+ video . pause ( ) ;
117+ }
118+ } ) ;
119+ } ,
120+ { threshold : 0.25 }
121+ ) ;
122+
123+ videos . forEach ( ( video ) => {
104124 observer . observe ( video ) ;
105- } ) ;
106- </ script >
125+ } ) ;
126+ </ script >
107127</ body >
108128
109129</ html >
You can’t perform that action at this time.
0 commit comments