Greasy Fork 支持简体中文。

super fast load

Enhance your browsing with Super Fast Load! Stop YouTube autoplay, add download buttons, and block ads, pop-ups, and trackers. Speed up slow connections, save data, and preload links for quick access. Hide cookie banners, disable location tracking, and block unnecessary scripts. Optimize for VPN/Tor, lazy load images and videos, and boost download speeds. Improve website loading by optimizing media elements and reducing ad buffering. Experience faster, safer browsing today!

// ==UserScript==
// @name         super fast load
// @namespace    http://tampermonkey.net/
// @version      3
// @description  Enhance your browsing with Super Fast Load! Stop YouTube autoplay, add download buttons, and block ads, pop-ups, and trackers. Speed up slow connections, save data, and preload links for quick access. Hide cookie banners, disable location tracking, and block unnecessary scripts. Optimize for VPN/Tor, lazy load images and videos, and boost download speeds. Improve website loading by optimizing media elements and reducing ad buffering. Experience faster, safer browsing today!
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @require      https://cdn.jsdelivr.net/npm/[email protected]/umd/browser/brotli.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/zstd/1.3.8/zstd.min.js
// @connect      * // این خط برای جلوگیری از پیغام دسترسی به منابع بین‌مرزی است
// ==/UserScript==

(function() {
    'use strict';

    const CONFIG = {
        resourceCache: new Map(),
        blockList: ['ads.example.com', 'tracking.example.com'],
        nonEssentialSelectors: ['script[src*="tracking"]', 'iframe[src*="advertisement"]', '.ad-banner', '.cookie-consent'],
        criticalResources: ['https://example.com/styles.css', 'https://example.com/script.js'],
        timeout: 500,
        maxRetries: 3,
        retryDelay: 1000,
        imageQuality: 50,
        preloadThreshold: 500,
        minifyCSS: true,
        minifyJS: true,
    };

    // Fetch with timeout
    const fetchWithTimeout = async (url, options = {}) => {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), CONFIG.timeout);
        try {
            const response = await fetch(url, { ...options, signal: controller.signal });
            clearTimeout(timeoutId);
            return response;
        } catch (error) {
            clearTimeout(timeoutId);
            throw error;
        }
    };

    // Inject CSS
    const injectCSS = (css) => {
        const style = document.createElement('style');
        style.textContent = css;
        document.head.appendChild(style);
    };

    // Preload links
    const preloadLinks = () => {
        const links = document.querySelectorAll('a[href]');
        links.forEach(link => {
            if (!CONFIG.resourceCache.has(link.href)) {
                const linkElement = document.createElement('link');
                linkElement.rel = 'prefetch';
                linkElement.href = link.href;
                document.head.appendChild(linkElement);
                CONFIG.resourceCache.set(link.href, true);
            }
        });
    };

    // Compress images
    const compressImage = async (img) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        ctx.drawImage(img, 0, 0);
        const compressedDataUrl = canvas.toDataURL('image/jpeg', CONFIG.imageQuality / 100);
        img.src = compressedDataUrl;
    };

    // Optimize images
    const optimizeImages = async () => {
        const images = document.querySelectorAll('img');
        images.forEach(async (img) => {
            if (img.complete && img.naturalWidth > 0) {
                await compressImage(img);
            }
        });
    };

    // Minify CSS
    const minifyCSS = (css) => {
        return css.replace(/\s+/g, ' ').trim();
    };

    // Minify JS
    const minifyJS = (js) => {
        return js.replace(/\s+/g, ' ').trim();
    };

    // Minify resources
    const minifyResources = async (url) => {
        const response = await fetch(url);
        if (!response.ok) throw new Error('Network response was not ok');
        const text = await response.text();
        if (url.endsWith('.css') && CONFIG.minifyCSS) {
            return minifyCSS(text);
        } else if (url.endsWith('.js') && CONFIG.minifyJS) {
            return minifyJS(text);
        }
        return text;
    };

    // Load resource
    const loadResource = async (url, type) => {
        try {
            const text = await minifyResources(url);
            const blob = new Blob([text], { type: type === 'css' ? 'text/css' : 'application/javascript' });
            const blobUrl = URL.createObjectURL(blob);
            const element = document.createElement(type === 'css' ? 'link' : 'script');
            element[type === 'css' ? 'href' : 'src'] = blobUrl;
            element.rel = type === 'css' ? 'stylesheet' : undefined;
            element.defer = type !== 'css';
            document.head.appendChild(element);
        } catch (error) {
            console.error('Failed to load resource:', url, error);
        }
    };

    // Preload critical resources
    const preloadResources = () => {
        CONFIG.criticalResources.forEach(resource => {
            loadResource(resource, resource.endsWith('.css') ? 'css' : 'js');
        });
    };

    // Block unnecessary requests
    const blockUnnecessaryRequests = () => {
        const originalOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function (method, url, ...args) {
            if (url.includes('captcha') || url.includes('cloudflare')) {
                return originalOpen.call(this, method, url, ...args);
            }
            if (CONFIG.blockList.some(domain => url.includes(domain))) {
                console.log(`Blocked request to: ${url}`);
                return;
            }
            return originalOpen.call(this, method, url, ...args);
        };
    };

    // Prevent data collection
    const preventDataCollection = () => {
        navigator.geolocation.getCurrentPosition = () => console.warn("Geolocation access blocked.");
        Object.defineProperty(navigator, 'userAgent', { get: () => 'Blocked User Agent' });
    };

    // Remove non-essential elements
    const removeNonEssentialElements = () => {
        CONFIG.nonEssentialSelectors.forEach(selector => {
            document.querySelectorAll(selector).forEach(element => {
                if (!element.src?.includes('captcha') && !element.src?.includes('cloudflare')) {
                    element.remove();
                }
            });
        });
    };

    // Prevent autoplay without breaking video controls
    const preventAutoplay = () => {
        const stopAutoplay = (media) => {
            media.pause(); // Stop autoplay
            media.preload = 'none'; // Prevent preloading
            media.autoplay = false; // Disable autoplay
            media.setAttribute('data-autoplay-prevented', 'true'); // Mark video as autoplay prevented

            // Control play/pause with mouse click
            media.addEventListener('click', (event) => {
                event.stopPropagation(); // Prevent event propagation
                if (media.paused) {
                    media.play(); // Play if paused
                } else {
                    media.pause(); // Pause if playing
                }
            });

            media.controls = false; // Disable default video controls

            // Hide large/small play buttons (if present)
            const playButton = media.closest('.ytp-large-play-button, .ytp-small-play-button');
            if (playButton) {
                playButton.style.display = 'none';
            }
        };

        // Apply settings to all video and audio elements on the page
        document.querySelectorAll('video, audio').forEach(stopAutoplay);

        // Observe DOM changes to apply settings to new video and audio elements
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeName === 'VIDEO' || node.nodeName === 'AUDIO') {
                            stopAutoplay(node);
                        } else if (node.querySelectorAll) {
                            node.querySelectorAll('video, audio').forEach(stopAutoplay);
                        }
                    });
                }
            });
        });

        // Start observing the document body for changes
        observer.observe(document.body, { childList: true, subtree: true });
    };

    // Lazy load media
    const lazyLoadMedia = () => {
        const observer = new IntersectionObserver(entries => {
            entries.forEach(async entry => {
                if (entry.isIntersecting) {
                    const media = entry.target;
                    const response = await fetch(media.dataset.src);
                    if (response.ok) {
                        const blob = await response.blob();
                        media.src = URL.createObjectURL(blob);
                        observer.unobserve(media);
                    }
                }
            });
        }, { threshold: 0.1, rootMargin: '200px' });

        document.querySelectorAll('video[data-src], audio[data-src], img[data-src]').forEach(media => observer.observe(media));
    };

    // Enable lazy loading for images
    const enableLazyLoadImages = () => {
        document.querySelectorAll('img:not([loading])').forEach(img => {
            img.loading = 'lazy';
            img.decoding = 'async';
            img.referrerPolicy = 'no-referrer';
        });
    };

    // Create download button
    const createDownloadButton = () => {
        const downloadIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        downloadIcon.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        downloadIcon.setAttribute('fill', 'currentColor');
        downloadIcon.setAttribute('height', '24');
        downloadIcon.setAttribute('viewBox', '0 0 24 24');
        downloadIcon.setAttribute('width', '24');
        downloadIcon.setAttribute('focusable', 'false');
        downloadIcon.style.pointerEvents = 'none';
        downloadIcon.style.display = 'block';
        downloadIcon.style.width = '100%';
        downloadIcon.style.height = '100%';
        downloadIcon.style.opacity = '0.2';

        const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute('d', 'M17 18v1H6v-1h11zm-.5-6.6-.7-.7-3.8 3.7V4h-1v10.4l-3.8-3.8-.7.7 5 5 5-4.9z');
        downloadIcon.appendChild(path);

        const downloadButton = document.createElement('button');
        downloadButton.id = 'ytdl-download-button';
        downloadButton.classList.add('ytp-button');
        downloadButton.title = 'Left click to download as video, right click as audio only';
        downloadButton.appendChild(downloadIcon);

        const interval = setInterval(() => {
            const controls = document.querySelector('.ytp-right-controls');
            if (controls && !document.getElementById('ytdl-download-button')) {
                controls.insertBefore(downloadButton, controls.firstChild);
                clearInterval(interval);
            }
        }, 1000);

        downloadButton.addEventListener('click', (event) => {
            if (event.button === 0) {
                showModal();
            } else if (event.button === 2) {
                showModal(true);
            }
        });
    };

    // Show modal
    const showModal = (isAudioOnly = false) => {
        const overlay = document.createElement('div');
        overlay.id = 'modal-overlay';
        overlay.onclick = hideModal;

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

        const iframe = document.createElement('iframe');
        const videoID = new URLSearchParams(window.location.search).get('v');
        if (videoID) {
            const url = isAudioOnly ? `https://www.y2mate.com/youtube/${videoID}/audio` : `https://www.y2mate.com/youtube/${videoID}`;
            iframe.src = url;
        }
        modalContent.appendChild(iframe);
        overlay.appendChild(modalContent);
        document.body.appendChild(overlay);

        overlay.style.display = 'flex';
    };

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

    // Monitor connection
    const monitorConnection = async () => {
        while (true) {
            try {
                const response = await fetch('https://www.google.com/generate_204', { method: 'GET', mode: 'no-cors' });
                if (response.status >= 200 && response.status < 300) {
                    console.log("Internet is stable.");
                } else {
                    throw new Error("Connectivity issue detected.");
                }
            } catch (error) {
                console.warn("Internet connection lost! Attempting to reconnect...");
                reconnectNetwork();
            }
            await new Promise(resolve => setTimeout(resolve, 3000));
        }
    };

    // Reconnect network
    const reconnectNetwork = async () => {
        console.log("Reconnecting to the network...");
        try {
            await clearDNSCache();
            console.log("DNS cache cleared.");
            navigator.serviceWorker.getRegistrations().then(registrations => {
                registrations.forEach(reg => reg.unregister());
                console.log("Service workers reset.");
            });
            if (navigator.connection && navigator.connection.type) {
                navigator.connection.type = "wifi";
                console.log("Network interface reinitialized.");
            }
            console.log("Reconnection attempt completed.");
        } catch (error) {
            console.error("Error during reconnection process:", error);
        }
    };

    // Clear DNS cache
    const clearDNSCache = async () => {
        try {
            await Promise.all([
                fetch('https://1.1.1.1/generate_204', { method: 'GET', mode: 'no-cors' }),
                fetch('https://8.8.8.8/generate_204', { method: 'GET', mode: 'no-cors' }),
            ]);
            console.log("DNS cache refreshed.");
        } catch (error) {
            console.warn("Failed to refresh DNS cache:", error);
        }
    };

    // Enhance request stability
    const enhanceRequestStability = () => {
        const originalFetch = window.fetch;
        window.fetch = async (...args) => {
            for (let attempt = 1; attempt <= CONFIG.maxRetries; attempt++) {
                try {
                    const response = await originalFetch(...args);
                    if (response.ok) return response;
                } catch (error) {
                    console.warn(`Fetch attempt ${attempt} failed. Retrying...`, error);
                }
                await new Promise(resolve => setTimeout(resolve, CONFIG.retryDelay));
            }
            console.error("Fetch failed after 5 retries.");
            throw new Error("Failed to stabilize request.");
        };

        const originalXMLHttpRequest = window.XMLHttpRequest;
        window.XMLHttpRequest = function () {
            const xhr = new originalXMLHttpRequest();
            xhr.addEventListener("error", () => {
                console.warn("XHR failed. Retrying...");
                setTimeout(() => xhr.open(xhr.method, xhr.url, true), CONFIG.retryDelay);
            });
            return xhr;
        };
    };

    // Optimize based on conditions
    const optimizeBasedOnConditions = async () => {
        const networkInfo = await getNetworkInfo();
        const deviceInfo = getDeviceInfo();

        console.log('Network Info:', networkInfo);
        console.log('Device Info:', deviceInfo);

        if (networkInfo.effectiveType === 'slow-2g' || networkInfo.effectiveType === '2g') {
            console.log('Slow network detected. Applying aggressive optimizations...');
            preloadResources();
            enhanceRequestStability();
            enableLazyLoadImages();
            optimizeImages();
        } else if (networkInfo.effectiveType === '3g') {
            console.log('3G network detected. Applying moderate optimizations...');
            preloadResources();
            enableLazyLoadImages();
            optimizeImages();
        } else {
            console.log('Fast network detected. Applying light optimizations...');
            enableLazyLoadImages();
            optimizeImages();
        }
    };

    // Check if mobile
    const isMobile = () => window.matchMedia('(max-width: 768px)').matches;

    // Save mobile resources
    const saveMobileResources = () => {
        const elements = document.querySelectorAll('img[src], video[src], script[src], link[rel="stylesheet"]');
        const mobileResources = new Set();
        elements.forEach(el => {
            const src = el.src || el.href;
            if (src) {
                mobileResources.add(src);
            }
        });
        sessionStorage.setItem('mobileResources', JSON.stringify([...mobileResources]));
        console.log('Mobile resources captured:', [...mobileResources]);
    };

    // Block desktop resources
    const blockDesktopResources = () => {
        const storedResources = sessionStorage.getItem('mobileResources');
        if (!storedResources) {
            console.warn('No mobile resources found. Please visit the site in mobile mode first.');
            return;
        }
        const mobileResources = new Set(JSON.parse(storedResources));

        const blockRequest = (url) => {
            if (!mobileResources.has(url)) {
                console.warn(`Blocked desktop-only resource: ${url}`);
                return true;
            }
            return false;
        };

        const originalFetch = window.fetch;
        window.fetch = function (...args) {
            if (blockRequest(args[0])) {
                return Promise.reject(new Error('Blocked by Tampermonkey script'));
            }
            return originalFetch.apply(this, args);
        };

        const originalXHR = window.XMLHttpRequest.prototype.open;
        window.XMLHttpRequest.prototype.open = function (method, url, ...rest) {
            if (blockRequest(url)) {
                console.warn(`Blocked XHR request: ${url}`);
                return;
            }
            return originalXHR.apply(this, [method, url, ...rest]);
        };
    };

    // Improve page cache
    const improvePageCache = () => {
        const cacheKey = 'pageCache';
        const cachedData = localStorage.getItem(cacheKey);
        if (cachedData) {
            const parsedData = JSON.parse(cachedData);
            console.log('Loaded from cache:', parsedData);
        } else {
            console.log('No cache found. Creating new cache...');
            localStorage.setItem(cacheKey, JSON.stringify({ timestamp: Date.now(), data: 'example data' }));
        }
    };

    // Lazy load all elements
    const lazyLoadAllElements = () => {
        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const element = entry.target;
                    if (element.tagName === 'IMG' && element.dataset.src) {
                        element.src = element.dataset.src;
                    } else if (element.tagName === 'VIDEO' && element.dataset.src) {
                        element.src = element.dataset.src;
                    } else if (element.tagName === 'IFRAME' && element.dataset.src) {
                        element.src = element.dataset.src;
                    } else if (element.tagName === 'DIV' && element.dataset.style) {
                        element.style = element.dataset.style;
                    }
                    observer.unobserve(element);
                }
            });
        }, { threshold: 0.1, rootMargin: '200px' });

        document.querySelectorAll('img[data-src], video[data-src], iframe[data-src], div[data-style]').forEach(element => observer.observe(element));
    };

    // Function to optimize media elements
    const optimizeMediaElements = () => {
        const mediaElements = document.querySelectorAll('video, audio');
        mediaElements.forEach(media => {
            media.preload = 'auto';
            media.autoplay = false;
            media.loop = false;
            media.controls = true;
            media.muted = false;
        });
    };

    // Function to block ad-related scripts
    const blockAdScripts = () => {
        const scripts = document.querySelectorAll('script');
        scripts.forEach(script => {
            if (script.src && script.src.includes('ads')) {
                script.remove();
            }
        });
    };

    // Function to optimize network requests
    const optimizeNetworkRequests = () => {
        const originalFetch = window.fetch;
        window.fetch = function(resource, init) {
            const url = typeof resource === 'string' ? resource : resource.url;
            if (url.includes('ads') || url.includes('tracking')) {
                return Promise.reject(new Error('Blocked ad or tracking request'));
            }
            return originalFetch(resource, init);
        };
    };

    // Function to delay non-essential scripts
    const delayNonEssentialScripts = () => {
        const scripts = document.querySelectorAll('script[type="text/javascript"]');
        scripts.forEach(script => {
            if (!script.src && !script.async && !script.defer) {
                script.defer = true;
            }
        });
    };

    // Inject CSS
    injectCSS(`
        #ytdl-download-button {
            position: relative;
            top: 0;
            left: 0;
            background-color: transparent;
            border: none;
            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;
        }

        #modal-content iframe {
            width: 100%;
            height: 400px;
            border: none;
        }

        .ytp-large-play-button, .ytp-small-play-button {
            display: none !important;
        }

        video::-webkit-media-controls {
            display: none !important;
        }
    `);

    // Initialize optimizations
    preloadResources();
    monitorConnection();
    enhanceRequestStability();
    optimizeBasedOnConditions();
    blockUnnecessaryRequests();
    preventDataCollection();
    removeNonEssentialElements();
    preventAutoplay();
    lazyLoadMedia();
    enableLazyLoadImages();
    optimizeImages();
    preloadLinks();
    improvePageCache();
    lazyLoadAllElements();
    optimizeMediaElements();
    blockAdScripts();
    optimizeNetworkRequests();
    delayNonEssentialScripts();

    // Event listeners
    window.addEventListener('yt-navigate-finish', () => {
        preventAutoplay();
        createDownloadButton();
    });

    window.addEventListener('load', () => {
        preventAutoplay();
        createDownloadButton();
    });

    const originalPushState = history.pushState;
    history.pushState = function() {
        originalPushState.apply(this, arguments);
        preventAutoplay();
    };

    const originalReplaceState = history.replaceState;
    history.replaceState = function() {
        originalReplaceState.apply(this, arguments);
        preventAutoplay();
    };

    // Mobile/desktop detection
    if (isMobile()) {
        console.log('Mobile mode detected. Capturing resources...');
        saveMobileResources();
    } else {
        console.log('Desktop mode detected. Blocking extra resources...');
        blockDesktopResources();
    }

    console.log("Ultimate Page Load Optimizer with Advanced Lazy Loading and Speed Up Website Loading is active.");
})();