Lazy Load Videos

Accelerate video loading by lazy loading videos

// ==UserScript==
// @name         Lazy Load Videos
// @namespace    http://tampermonkey.net/
// @version      1.4
// @description  Accelerate video loading by lazy loading videos
// @author       tae
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Function to lazy load videos
    function lazyLoadVideos() {
        const videos = document.querySelectorAll('video');
        const config = {
            rootMargin: '0px 0px 50px 0px',
            threshold: 0.00
        };

        let observer;
        if ('IntersectionObserver' in window) {
            observer = new IntersectionObserver((entries, self) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        let video = entry.target;
                        video.src = video.dataset.src;
                        video.load();
                        video.pause(); // Ensure the video is paused before loading
                        self.unobserve(video);
                    }
                });
            }, config);

            videos.forEach(video => {
                if (video.dataset.src) {
                    observer.observe(video);
                }
            });
        } else {
            // Fallback for browsers that don't support IntersectionObserver
            const lazyLoadFallback = () => {
                videos.forEach(video => {
                    if (video.dataset.src) {
                        const rect = video.getBoundingClientRect();
                        if (rect.top < window.innerHeight && rect.bottom > 0) {
                            video.src = video.dataset.src;
                            video.load();
                            video.pause(); // Ensure the video is paused before loading
                        }
                    }
                });
            };

            document.addEventListener('scroll', lazyLoadFallback);
            window.addEventListener('resize', lazyLoadFallback);
            window.addEventListener('orientationchange', lazyLoadFallback);
            lazyLoadFallback(); // Initial check on page load
        }
    }

    // Initialize lazy loading when the DOM content is loaded
    window.addEventListener('DOMContentLoaded', lazyLoadVideos);
})();