Optimized Web Accelerator

Combina aceleração de renderização com economia de dados de forma segura e estável

K instalaci tototo skriptu si budete muset nainstalovat rozšíření jako Tampermonkey, Greasemonkey nebo Violentmonkey.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat manažer uživatelských skriptů.

(Už mám manažer uživatelských skriptů, nechte mě ho nainstalovat!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Už mám manažer uživatelských stylů, nechte mě ho nainstalovat!)

// ==UserScript==
// @name         Optimized Web Accelerator
// @namespace    https://github.com/optimized-web
// @version      1.0
// @description  Combina aceleração de renderização com economia de dados de forma segura e estável
// @author       Optimized Web Team
// @match        *://*/*
// @run-at       document-start
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // ==========================================
    // CONFIGURAÇÃO - Controle de funcionalidades
    // ==========================================
    const CONFIG = {
        // Performance (do PureRender)
        disableSmoothScroll: true,
        removeBlockingElements: true,
        disableHeavyEffects: true,
        unlockScroll: true,
        
        // Economia de Dados (do Ultra Data Saver - versão segura)
        blockTrackers: true,
        compressImages: true,
        blockAutoplay: true,
        removeWebFonts: false,        // Mantido false para não quebrar layouts
        removeAnimations: false,      // Mantido false para não quebrar UX
        lazyLoadImages: false,        // Usa eager do PureRender
        blockAggressiveAds: true,     // Apenas anúncios óbvios
        
        // Controles de segurança
        preserveMainContent: true,
        allowUserInteraction: true,
        smartBlocking: true
    };

    // ==========================================
    // EXCLUSÕES AUTOMÁTICAS
    // ==========================================
    const host = location.hostname;
    
    // YouTube já tem otimização própria
    if (host.includes("youtube.com") || host.includes("youtu.be")) return;
    
    // Sites críticos que não devem ser otimizados agressivamente
    const CRITICAL_SITES = [
        'github.com', 'stackoverflow.com', 'web.whatsapp.com',
        'mail.google.com', 'outlook.live.com', 'bankofamerica.com'
    ];
    
    if (CRITICAL_SITES.some(site => host.includes(site))) {
        CONFIG.blockAggressiveAds = false;
        CONFIG.compressImages = false;
    }

    // Exclusões do usuário
    const userExcluded = GM_getValue("excluded_sites", []) || [];
    if (userExcluded.includes(host)) return;

    // ==========================================
    // LISTAS DE BLOQUEIO (versão conservadora)
    // ==========================================
    const TRACKER_DOMAINS = [
        'google-analytics', 'googletagmanager', 'googlesyndication',
        'googleadservices', 'doubleclick', 'facebook.com/tr',
        'facebook.net', 'connect.facebook', 'analytics.twitter',
        'linkedin.com/analytics', 'adsystem', 'amazon-adsystem',
        'googletagservices', 'outbrain', 'taboola', 'scorecardresearch',
        'quantserve', 'hotjar', 'mixpanel', 'segment.io', 'amplitude'
    ];

    const AGGRESSIVE_AD_SELECTORS = [
        'ins.adsbygoogle', '.ad-container', '.ad-wrapper',
        '[class*="ad-"]', '[class*="ads-"]', '[id*="ad-"]',
        '[class*="advertisement"]', '[id*="advertisement"]'
    ];

    const BLOCKING_SELECTORS = [
        '[class*="preloader"]', '[id*="preloader"]', 
        '[class*="loading-overlay"]', '[class*="skeleton"]',
        '.loading', '.spinner', '#loader'
    ];

    // ==========================================
    // FUNÇÕES UTILITÁRIAS
    // ==========================================
    const isTracker = (url) => {
        if (!url) return false;
        const lowerUrl = url.toLowerCase();
        return TRACKER_DOMAINS.some(domain => lowerUrl.includes(domain));
    };

    const isAdElement = (element) => {
        return AGGRESSIVE_AD_SELECTORS.some(selector => {
            try {
                return element.matches && element.matches(selector);
            } catch (e) {
                return false;
            }
        });
    };

    const isBlockingElement = (element) => {
        return BLOCKING_SELECTORS.some(selector => {
            try {
                return element.matches && element.matches(selector);
            } catch (e) {
                return false;
            }
        });
    };

    // ==========================================
    // 1. ESTILOS DE OTIMIZAÇÃO (seguros)
    // ==========================================
    GM_addStyle(`
        /* Desabilitar smooth scroll para resposta instantânea */
        ${CONFIG.disableSmoothScroll ? `
        html, body {
            scroll-behavior: auto !important;
        }` : ''}

        /* Garantir visibilidade do conteúdo */
        html, body {
            visibility: visible !important;
            opacity: 1 !important;
        }

        /* Remover elementos bloqueantes */
        ${CONFIG.removeBlockingElements ? `
        ${BLOCKING_SELECTORS.join(', ')} {
            display: none !important;
            visibility: hidden !important;
            pointer-events: none !important;
        }` : ''}

        /* Reduzir efeitos pesados de GPU */
        ${CONFIG.disableHeavyEffects ? `
        * {
            backdrop-filter: none !important;
            -webkit-backdrop-filter: none !important;
            text-shadow: none !important;
            box-shadow: none !important;
        }` : ''}

        /* Otimização de renderização de imagem */
        img {
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
        }

        /* Animações mínimas (se habilitado) */
        ${CONFIG.removeAnimations ? `
        *, *::before, *::after {
            animation-duration: 0.01ms !important;
            animation-iteration-count: 1 !important;
            transition-duration: 0.01ms !important;
        }` : ''}
    `);

    // ==========================================
    // 2. BLOQUEIO DE RASTREADORES (seguro)
    // ==========================================
    if (CONFIG.blockTrackers) {
        // Intercepta fetch
        const originalFetch = window.fetch;
        window.fetch = function(...args) {
            const url = args[0] instanceof Request ? args[0].url : args[0];
            if (isTracker(url)) {
                return Promise.resolve(new Response('', { status: 200 }));
            }
            return originalFetch.apply(this, args);
        };

        // Intercepta scripts
        const originalAppendChild = Element.prototype.appendChild;
        Element.prototype.appendChild = function(node) {
            if (node.tagName === 'SCRIPT' && node.src && isTracker(node.src)) {
                return node;
            }
            return originalAppendChild.call(this, node);
        };
    }

    // ==========================================
    // 3. OTIMIZAÇÃO DE IMAGENS (segura)
    // ==========================================
    if (CONFIG.compressImages) {
        const optimizeImage = (img) => {
            // Não otimizar ícones pequenos
            if (img.width < 32 && img.height < 32) return;

            const src = img.src;
            if (!src || src.startsWith('data:')) return;

            // Otimização para CDNs conhecidos
            if (src.includes('googleusercontent') || src.includes('ggpht')) {
                img.src = src.replace(/=s\d+/, '=s800').replace(/=w\d+/, '=w800');
            } else if (src.includes('cloudinary')) {
                img.src = src.replace('/upload/', '/upload/q_auto:good,w_800/');
            }

            // Carregamento imediato (PureRender approach)
            img.loading = 'eager';
            img.decoding = 'async';
        };

        // Processar imagens existentes
        const processImages = () => {
            document.querySelectorAll('img').forEach(optimizeImage);
        };

        // Observer para novas imagens
        const imgObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.tagName === 'IMG') optimizeImage(node);
                    if (node.querySelectorAll) {
                        node.querySelectorAll('img').forEach(optimizeImage);
                    }
                });
            });
        });

        imgObserver.observe(document.body || document.documentElement, {
            childList: true,
            subtree: true
        });

        // Processar imagens quando disponíveis
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', processImages);
        } else {
            processImages();
        }
    }

    // ==========================================
    // 4. CONTROLE DE AUTOPLAY (seguro)
    // ==========================================
    if (CONFIG.blockAutoplay) {
        // Bloquear autoplay apenas se não for iniciado pelo usuário
        const originalPlay = HTMLMediaElement.prototype.play;
        HTMLMediaElement.prototype.play = function() {
            // Heurística simples: se não tiver interação do usuário, bloquear
            if (!this.hasAttribute('data-user-initiated') && 
                !this.closest('[data-user-interacted]')) {
                this.pause();
                this.muted = true;
                return Promise.resolve();
            }
            return originalPlay.call(this);
        };

        // Preparar elementos de mídia
        const prepareMedia = () => {
            document.querySelectorAll('video, audio').forEach(media => {
                media.preload = 'metadata';
                media.autoplay = false;
            });
        };

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', prepareMedia);
        } else {
            prepareMedia();
        }
    }

    // ==========================================
    // 5. REMOÇÃO DE ANÚNCIOS (conservadora)
    // ==========================================
    if (CONFIG.blockAggressiveAds) {
        const removeAds = () => {
            AGGRESSIVE_AD_SELECTORS.forEach(selector => {
                try {
                    document.querySelectorAll(selector).forEach(el => {
                        // Não remover conteúdo principal
                        if (el.tagName === 'ARTICLE' || el.tagName === 'MAIN' || 
                            el.tagName === 'SECTION') return;
                        
                        // Verificar se não é conteúdo importante
                        const hasContent = el.textContent.trim().length > 100;
                        if (!hasContent || isAdElement(el)) {
                            el.style.display = 'none';
                        }
                    });
                } catch (e) {
                    // Ignorar erros de seletor inválido
                }
            });
        };

        // Executar após carregamento
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', removeAds);
            setTimeout(removeAds, 2000);
        } else {
            removeAds();
            setTimeout(removeAds, 2000);
        }
    }

    // ==========================================
    // 6. LIBERAÇÃO DE SCROLL (PureRender)
    // ==========================================
    if (CONFIG.unlockScroll) {
        const unlockScroll = () => {
            const style = getComputedStyle(document.body);
            if (style.overflow === 'hidden' || style.position === 'fixed') {
                document.body.style.setProperty("overflow", "auto", "important");
                document.body.style.setProperty("position", "static", "important");
                document.documentElement.style.setProperty("overflow", "auto", "important");
            }
        };

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', unlockScroll);
            window.addEventListener('load', unlockScroll);
        } else {
            unlockScroll();
        }
    }

    // ==========================================
    // 7. MENU DE CONTROLE
    // ==========================================
    GM_registerMenuCommand("🚫 Excluir este site", () => {
        const currentExcluded = GM_getValue("excluded_sites", []);
        if (!currentExcluded.includes(host)) {
            currentExcluded.push(host);
            GM_setValue("excluded_sites", currentExcluded);
            location.reload();
        }
    });

    GM_registerMenuCommand("🔄 Limpar exclusões", () => {
        if (confirm("Limpar todas as exclusões de sites?")) {
            GM_setValue("excluded_sites", []);
            location.reload();
        }
    });

    // ==========================================
    // 8. INDICADOR VISUAL SUTIL
    // ==========================================
    window.addEventListener('load', () => {
        setTimeout(() => {
            const indicator = document.createElement('div');
            indicator.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                background: rgba(76, 175, 80, 0.9);
                color: white;
                padding: 8px 12px;
                border-radius: 4px;
                font-size: 11px;
                font-family: system-ui;
                z-index: 999999;
                pointer-events: none;
                opacity: 0;
                transition: opacity 0.3s;
            `;
            indicator.textContent = '⚡ Web Accelerator';
            document.body.appendChild(indicator);
            
            // Fade in e out
            setTimeout(() => indicator.style.opacity = '1', 100);
            setTimeout(() => {
                indicator.style.opacity = '0';
                setTimeout(() => indicator.remove(), 300);
            }, 3000);
        }, 1000);
    });

})();