index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function setup(videoEl) {
  2. const reducedMotionReduce = window.matchMedia(
  3. '(prefers-reduced-motion: reduce)'
  4. )
  5. if (reducedMotionReduce.matches) {
  6. // TODO: on firefox, if user enters this mode, video can throw error
  7. // in console, if user seeks the control seek bar relatively fast
  8. // AbortError: The fetching process for the media resource was aborted by the user agent at the user's request.
  9. // this is only a problem in firefox (tested in macOS), chrome and safari is fine
  10. videoEl.setAttribute('controls', '')
  11. return
  12. }
  13. const DELAY_BEFORE_REPLAY = 15 * 1000
  14. // 0.7 will enable the autoplay on the desktop main homepage video for all users
  15. const INTERSECTION_THRESHOLD = 0.7
  16. let videoIsVisible
  17. videoEl.addEventListener('ended', () => {
  18. setTimeout(() => {
  19. videoEl.currentTime = 0
  20. if (videoIsVisible) {
  21. videoEl.play()
  22. }
  23. }, DELAY_BEFORE_REPLAY)
  24. })
  25. const observer = new IntersectionObserver(
  26. function onIntersecting(changes) {
  27. for (const change of changes) {
  28. if (change.isIntersecting) {
  29. videoIsVisible = true
  30. if (videoEl.readyState >= videoEl.HAVE_FUTURE_DATA) {
  31. if (!videoEl.ended) {
  32. videoEl.play()
  33. }
  34. } else {
  35. videoEl.play()
  36. }
  37. } else {
  38. videoIsVisible = false
  39. }
  40. }
  41. },
  42. {
  43. threshold: INTERSECTION_THRESHOLD,
  44. }
  45. )
  46. observer.observe(videoEl)
  47. }
  48. document.querySelectorAll('[data-ol-autoplay-video]').forEach(setup)