index.js 1.8 KB

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