Greasy Fork

Greasy Fork is available in English.

Super Fast Loading

Optimize loading for slow and unstable internet connections, prevent autoplay for YouTube, add download button with quality selection, lazy load images and videos, boost website loading speed with multiple concurrent connections, and optimize loading for specific websites, with enhanced support for Tor & VPN networks.

目前为 2024-11-27 提交的版本。查看 最新版本

// ==UserScript==
// @name         Super Fast Loading
// @namespace    http://greasyfork.icu/en/scripts/517138-super-fast-loading
// @version      1.6
// @description  Optimize loading for slow and unstable internet connections, prevent autoplay for YouTube, add download button with quality selection, lazy load images and videos, boost website loading speed with multiple concurrent connections, and optimize loading for specific websites, with enhanced support for Tor & VPN networks.
// @author       cavalier
// @match        *://*/*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    const allowAutoPlayWithinMillisecondsOfClick = 1000;
    let lastClickTimeMs = 0;

    // Cache to store loaded resources
    const resourceCache = new Set();

    // Array of URLs to optimize loading
    const optimizationUrls = [
        'https://example1.com/resource.js',
        'https://example2.com/styles.css',
        // Add more URLs as needed
    ];

    // Function to create download with multiple connections and error handling for Tor & VPN
    const downloadWithMultipleConnections = async (url, connections = 8) => {
        if (resourceCache.has(url)) {
            console.log(`Resource ${url} already loaded from cache.`);
            return null; // Return null if already cached
        }

        try {
            const response = await fetch(url, { cache: 'force-cache', mode: 'no-cors' });
            if (!response.ok) throw new Error('Network response was not ok');
            const blob = await response.blob();
            resourceCache.add(url); // Add to cache
            return URL.createObjectURL(blob);
        } catch (error) {
            console.error('Download error (retrying):', error);

            // Retry logic for unstable connections
            for (let attempt = 1; attempt <= 3; attempt++) {
                try {
                    const response = await fetch(url, { cache: 'force-cache', mode: 'no-cors' });
                    if (response.ok) {
                        const blob = await response.blob();
                        resourceCache.add(url);
                        return URL.createObjectURL(blob);
                    }
                } catch (retryError) {
                    console.error(`Retry ${attempt} failed for ${url}`, retryError);
                }
            }

            return null;
        }
    };

    // Function to prevent autoplay for YouTube videos with fallback mechanisms
    const preventAutoplayYouTube = () => {
        const videos = document.querySelectorAll('video');
        videos.forEach(video => {
            video.pause();
            video.removeAttribute('src');
            video.autoplay = false; // Ensure autoplay is disabled
            video.addEventListener('click', async () => {
                if (!video.src) {
                    const source = video.getAttribute('data-src');
                    if (source) {
                        const blobUrl = await downloadWithMultipleConnections(source);
                        if (blobUrl) {
                            video.src = blobUrl;
                            video.play();
                        }
                    }
                }
            });
        });
    };

    // Lazy load videos with multiple connections, optimized for Tor & VPN
    const lazyLoadVideos = () => {
        const videos = document.querySelectorAll('video[data-src]');
        const observer = new IntersectionObserver(entries => {
            entries.forEach(async entry => {
                if (entry.isIntersecting) {
                    const video = entry.target;
                    const blobUrl = await downloadWithMultipleConnections(video.getAttribute('data-src'));
                    if (blobUrl) {
                        video.src = blobUrl;
                        video.play();
                        observer.unobserve(video);
                    }
                }
            });
        }, { threshold: 0.5 }); // Adjusted threshold for Tor/VPN reliability

        videos.forEach(video => observer.observe(video));
    };

    // Enable lazy loading for images with additional optimization
    const enableLazyLoadImages = () => {
        const images = document.querySelectorAll('img:not([loading])');
        images.forEach(img => {
            img.setAttribute('loading', 'lazy');
            img.setAttribute('referrerpolicy', 'no-referrer'); // Enhanced privacy for Tor
        });
    };

    // Function to remove unnecessary elements for improved loading speed
    const removeNonEssentialElements = () => {
        const nonEssentialSelectors = [
            'script[src*="tracking"]', // Example: Scripts for tracking
            'iframe[src*="advertisement"]', // Example: Advertisement iframes
            '.ad-banner', // Example: Ad banners
            '.cookie-consent', // Example: Cookie consent banners
            // Add other non-essential selectors as needed
        ];

        nonEssentialSelectors.forEach(selector => {
            document.querySelectorAll(selector).forEach(element => {
                element.remove(); // Remove elements that match the selector
            });
        });
    };

    // Load scripts asynchronously with error handling
    const loadScriptAsync = async (url) => {
        const blobUrl = await downloadWithMultipleConnections(url);
        if (blobUrl) {
            const script = document.createElement('script');
            script.src = blobUrl;
            script.defer = true;
            document.head.appendChild(script);
        }
    };

    // Load CSS immediately with enhanced error handling
    const loadCSS = async (url) => {
        const blobUrl = await downloadWithMultipleConnections(url);
        if (blobUrl) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = blobUrl;
            document.head.appendChild(link);
        }
    };

    // Preload critical resources at the start, with enhanced Tor/VPN support
    const preloadResources = async () => {
        const criticalResources = [
            'https://example.com/styles.css',
            'https://example.com/script.js',
            // Add other resources here as needed
        ];

        criticalResources.forEach(resource => {
            if (resource.endsWith('.css')) {
                loadCSS(resource);
            } else if (resource.endsWith('.js')) {
                loadScriptAsync(resource);
            }
        });

        // Optimize loading for specific URLs
        optimizationUrls.forEach(url => {
            if (url.endsWith('.css')) {
                loadCSS(url);
            } else if (url.endsWith('.js')) {
                loadScriptAsync(url);
            }
        });
    };

    // Add custom CSS styles for the download button with improved compatibility
    GM_addStyle(`
        #custom-download-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #3399ff; /* Pastel blue */
            color: white;
            border: none;
            padding: 10px 28px;
            border-radius: 25px;
            font-size: 14px;
            cursor: pointer;
            z-index: 1000;
        }

        #modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }

        #modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
            overflow: hidden;
        }

        /* Adjust iframe settings */
        #modal-content iframe {
            width: 100%;
            height: 400px;
            border: none;
        }
    `);

    // Create download button
    function createDownloadButton() {
        const downloadButton = document.createElement('button');
        downloadButton.id = 'custom-download-button';
        downloadButton.innerText = 'VIDEO DOWNLOAD';
        downloadButton.onclick = showModal;

        // Add the button to the YouTube video controls
        const interval = setInterval(() => {
            const controls = document.querySelector('.ytp-right-controls');
            if (controls && !document.getElementById('custom-download-button')) {
                controls.insertBefore(downloadButton, controls.firstChild);
                clearInterval(interval);
            }
        }, 1000);
    }

    // Display modal
    function showModal() {
        const overlay = document.createElement('div');
        overlay.id = 'modal-overlay';
        overlay.onclick = hideModal;

        const modalContent = document.createElement('div');
        modalContent.id = 'modal-content';

        // Create iframe for y2mate site
        const iframe = document.createElement('iframe');
        const videoID = window.location.href.split('v=')[1]?.split('&')[0];
        if (videoID) {
            iframe.src = `https://www.y2mate.com/youtube/${videoID}`;
        }
        modalContent.appendChild(iframe);
        overlay.appendChild(modalContent);
        document.body.appendChild(overlay);

        overlay.style.display = 'flex';
    }

    // Hide modal
    function hideModal() {
        const overlay = document.getElementById('modal-overlay');
        if (overlay) {
            overlay.remove();
        }
    }

    // Run code when page loads
    window.addEventListener('yt-navigate-finish', () => {
        preventAutoplayYouTube();
        createDownloadButton();
    });

    // Execute code on initial load with improved handling for Tor/VPN
    window.onload = () => {
        preventAutoplayYouTube();
        enableLazyLoadImages();
        lazyLoadVideos();
        preloadResources();
        removeNonEssentialElements();
        createDownloadButton();
    };
})();