// ==UserScript== // @name 性能优化大师 - 网页加速与资源节省 // @namespace http://tampermonkey.net/ // @version 1.4.0 // @description 全面提升网页性能:禁用冗余动画、原生图片懒加载、拦截跟踪脚本、清理控制台噪音。新增视频优化、懒加载iframe、扩展跟踪黑名单。节省CPU/带宽,让浏览更流畅。 // @author PerformanceOptimizer // @match *://*/* // @grant GM_setValue // @grant GM_getValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_addStyle // @run-at document-start // @license MIT // ==/UserScript== (function() { 'use strict'; // ---------- 配置管理 ---------- const defaultConfig = { disableAnimations: true, // 禁用/缩减CSS动画和过渡效果 lazyLoadImages: true, // 为所有图片添加原生 loading="lazy" 和 decoding="async" blockTrackers: true, // 阻止常见跟踪/广告脚本加载 silenceConsole: false, // 静默控制台输出 (清空不必要的log) videoOptimization: true, // 视频优化:禁用自动播放、设置preload="none" lazyIframes: true // 懒加载iframe:仅当接近可视区时才加载 }; let config = { disableAnimations: GM_getValue('disableAnimations', defaultConfig.disableAnimations), lazyLoadImages: GM_getValue('lazyLoadImages', defaultConfig.lazyLoadImages), blockTrackers: GM_getValue('blockTrackers', defaultConfig.blockTrackers), silenceConsole: GM_getValue('silenceConsole', defaultConfig.silenceConsole), videoOptimization: GM_getValue('videoOptimization', defaultConfig.videoOptimization), lazyIframes: GM_getValue('lazyIframes', defaultConfig.lazyIframes) }; // 跟踪脚本黑名单 (域名或URL片段,匹配则阻止加载) - 增强版v1.4.0 const TRACKER_BLACKLIST = [ // 原有 'google-analytics.com', 'googletagmanager.com', 'googleadservices.com', 'doubleclick.net', 'facebook.net', 'facebook.com/tr', 'twitter.com/analytics', 'amazon-adsystem.com', 'scorecardresearch.com', 'hotjar.com', 'clarity.ms', 'mixpanel.com', 'segment.com', 'fullstory.com', 'yandexmetrica', 'baidu.com/hm.js', 'cnzz.com', '51.la', 'matomo.js', 'newrelic.com', 'optimizely.com', 'adsrvr.org', 'exelator.com', // 新增扩展 (v1.4.0) 'googletagservices.com', 'adservice.google.com', 'criteo.com', 'outbrain.com', 'taboola.com', 'adroll.com', 'zedo.com', 'adform.net', 'adnxs.com', 'rubiconproject.com', 'openx.net', 'pubmatic.com', 'indexww.com', 'casalemedia.com', 'contextweb.com', 'appnexus.com', 'bidswitch.net', 'bluekai.com', 'everesttech.net', 'flashtalking.com', 'amazon-adsystem.com' ]; // 保存菜单项ID let menuIds = {}; // 全局观察器实例 let mutationObserver = null; // 图片懒加载观察器 let scriptObserver = null; // 脚本拦截观察器 let videoObserver = null; // 视频优化观察器 let iframeObserver = null; // iframe懒加载观察器 (用于监控新增iframe) let iframeIntersectionObserver = null; // IntersectionObserver实例 (用于懒加载) let styleNode = null; // 注入的样式节点 // ---------- 工具函数 ---------- function saveConfig() { for (const [key, value] of Object.entries(config)) { GM_setValue(key, value); } } // 更新菜单项的勾选状态 function refreshMenuCommands() { for (const id of Object.values(menuIds)) { if (id) GM_unregisterMenuCommand(id); } menuIds = {}; menuIds.disableAnimations = GM_registerMenuCommand( `${config.disableAnimations ? '✅' : '❌'} 禁用CSS动画/过渡`, () => { config.disableAnimations = !config.disableAnimations; saveConfig(); toggleAnimations(config.disableAnimations); refreshMenuCommands(); } ); menuIds.lazyLoadImages = GM_registerMenuCommand( `${config.lazyLoadImages ? '✅' : '❌'} 原生图片懒加载`, () => { config.lazyLoadImages = !config.lazyLoadImages; saveConfig(); toggleLazyLoad(config.lazyLoadImages); refreshMenuCommands(); } ); menuIds.blockTrackers = GM_registerMenuCommand( `${config.blockTrackers ? '✅' : '❌'} 屏蔽跟踪/广告脚本`, () => { config.blockTrackers = !config.blockTrackers; saveConfig(); toggleTrackerBlocking(config.blockTrackers); refreshMenuCommands(); } ); menuIds.silenceConsole = GM_registerMenuCommand( `${config.silenceConsole ? '✅' : '❌'} 静默控制台`, () => { config.silenceConsole = !config.silenceConsole; saveConfig(); toggleConsoleSilence(config.silenceConsole); refreshMenuCommands(); } ); menuIds.videoOptimization = GM_registerMenuCommand( `${config.videoOptimization ? '✅' : '❌'} 视频优化 (禁用自动播放/preload=none)`, () => { config.videoOptimization = !config.videoOptimization; saveConfig(); toggleVideoOptimization(config.videoOptimization); refreshMenuCommands(); } ); menuIds.lazyIframes = GM_registerMenuCommand( `${config.lazyIframes ? '✅' : '❌'} 懒加载iframe (延迟加载)`, () => { config.lazyIframes = !config.lazyIframes; saveConfig(); toggleLazyIframes(config.lazyIframes); refreshMenuCommands(); } ); } // ---------- 优化模块 1: 禁用/缩减动画 ---------- function injectAnimationStyles(enable) { if (styleNode && styleNode.parentNode) styleNode.remove(); if (!enable) return; const css = ` /* 性能优化大师 - 禁用动画/过渡 (除非必要) */ *, *::before, *::after { animation-duration: 0.001s !important; transition-duration: 0.001s !important; animation-iteration-count: 1 !important; scroll-behavior: auto !important; } `; styleNode = GM_addStyle(css); } function toggleAnimations(enable) { if (enable) { injectAnimationStyles(true); } else { if (styleNode && styleNode.parentNode) styleNode.remove(); styleNode = null; } } // ---------- 优化模块 2: 原生图片懒加载 + decoding async ---------- function applyLazyLoadToImage(img) { if (!img || img.hasAttribute('data-optimized')) return; if (img.getAttribute('loading') === 'eager') return; if (!img.loading) img.loading = 'lazy'; if (!img.decoding) img.decoding = 'async'; img.setAttribute('data-optimized', 'lazy'); } function enableLazyLoad() { document.querySelectorAll('img:not([data-optimized])').forEach(applyLazyLoadToImage); if (mutationObserver) mutationObserver.disconnect(); mutationObserver = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'IMG') { applyLazyLoadToImage(node); } else if (node.querySelectorAll) { node.querySelectorAll('img:not([data-optimized])').forEach(applyLazyLoadToImage); } } }); } } }); mutationObserver.observe(document.documentElement, { childList: true, subtree: true }); } function disableLazyLoad() { if (mutationObserver) { mutationObserver.disconnect(); mutationObserver = null; } document.querySelectorAll('img[data-optimized]').forEach(img => { if (img.loading === 'lazy') img.loading = ''; if (img.decoding === 'async') img.decoding = ''; img.removeAttribute('data-optimized'); }); } function toggleLazyLoad(enable) { if (enable) enableLazyLoad(); else disableLazyLoad(); } // ---------- 优化模块 3: 屏蔽跟踪/广告脚本 ---------- function isTrackerScript(src) { if (!src) return false; const lowerSrc = src.toLowerCase(); return TRACKER_BLACKLIST.some(tracker => lowerSrc.includes(tracker)); } function handleScriptElement(script) { if (!config.blockTrackers) return false; const src = script.src || script.getAttribute('src'); if (src && isTrackerScript(src)) { script.remove(); if (!config.silenceConsole) { console.log('[性能优化] 已阻止跟踪脚本:', src); } return true; } return false; } function enableTrackerBlocking() { if (scriptObserver) scriptObserver.disconnect(); document.querySelectorAll('script[src]').forEach(handleScriptElement); scriptObserver = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'SCRIPT') { handleScriptElement(node); } else if (node.querySelectorAll) { node.querySelectorAll('script[src]').forEach(handleScriptElement); } } }); } } }); scriptObserver.observe(document.documentElement, { childList: true, subtree: true }); } function disableTrackerBlocking() { if (scriptObserver) { scriptObserver.disconnect(); scriptObserver = null; } } function toggleTrackerBlocking(enable) { if (enable) enableTrackerBlocking(); else disableTrackerBlocking(); } // ---------- 优化模块 4: 静默控制台 ---------- let originalConsole = {}; let consoleOverridden = false; function enableConsoleSilence() { if (consoleOverridden) return; const methods = ['log', 'warn', 'info', 'debug', 'error']; methods.forEach(method => { originalConsole[method] = console[method]; console[method] = function() {}; }); consoleOverridden = true; } function disableConsoleSilence() { if (!consoleOverridden) return; for (const [method, fn] of Object.entries(originalConsole)) { if (console[method] !== fn) { console[method] = fn; } } consoleOverridden = false; } function toggleConsoleSilence(enable) { if (enable) enableConsoleSilence(); else disableConsoleSilence(); } // ---------- 优化模块 5: 视频优化 (禁用自动播放/预加载) ---------- function applyVideoOptimization(video) { if (!video || video.hasAttribute('data-video-optimized')) return; // 阻止自动播放 if (video.hasAttribute('autoplay')) { video.removeAttribute('autoplay'); // 尝试暂停已自动播放的视频 if (!video.paused) { video.pause().catch(e => {}); // 忽略可能的暂停错误 } } // 设置预加载为none,减少带宽消耗 if (video.getAttribute('preload') !== 'none') { video.setAttribute('preload', 'none'); } // 可选:移除loop属性(用户可自行决定,为更节能可取消注释) // if (video.hasAttribute('loop')) video.removeAttribute('loop'); video.setAttribute('data-video-optimized', 'true'); } function enableVideoOptimization() { // 处理现有视频 document.querySelectorAll('video:not([data-video-optimized])').forEach(applyVideoOptimization); // 监听新增视频 if (videoObserver) videoObserver.disconnect(); videoObserver = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'VIDEO') { applyVideoOptimization(node); } else if (node.querySelectorAll) { node.querySelectorAll('video:not([data-video-optimized])').forEach(applyVideoOptimization); } } }); } } }); videoObserver.observe(document.documentElement, { childList: true, subtree: true }); } function disableVideoOptimization() { if (videoObserver) { videoObserver.disconnect(); videoObserver = null; } // 恢复所有视频的原始属性?(保持简单,仅停止优化行为,不清除已有标记) document.querySelectorAll('video[data-video-optimized]').forEach(video => { // 可选择恢复preload,但可能影响性能,默认不恢复 video.removeAttribute('data-video-optimized'); }); } function toggleVideoOptimization(enable) { if (enable) enableVideoOptimization(); else disableVideoOptimization(); } // ---------- 优化模块 6: 懒加载iframe (IntersectionObserver) ---------- // 存储待观察的iframe元素 let iframesToLazy = new Set(); function setupIframeLazyLoading(iframe) { if (!iframe || iframe.hasAttribute('data-iframe-lazy') || iframe.hasAttribute('data-lazy-loaded')) return; const originalSrc = iframe.src; if (!originalSrc || originalSrc === 'about:blank' || originalSrc.startsWith('javascript:')) return; // 存储原始src并清空src,避免立即加载 iframe.setAttribute('data-src', originalSrc); iframe.src = 'about:blank'; iframe.setAttribute('data-iframe-lazy', 'pending'); // 添加到IntersectionObserver观察 if (iframeIntersectionObserver) { iframeIntersectionObserver.observe(iframe); iframesToLazy.add(iframe); } } function loadIframe(iframe) { if (!iframe || iframe.hasAttribute('data-lazy-loaded')) return; const dataSrc = iframe.getAttribute('data-src'); if (dataSrc) { iframe.src = dataSrc; iframe.removeAttribute('data-src'); iframe.setAttribute('data-lazy-loaded', 'true'); iframe.removeAttribute('data-iframe-lazy'); } if (iframeIntersectionObserver && iframesToLazy.has(iframe)) { iframeIntersectionObserver.unobserve(iframe); iframesToLazy.delete(iframe); } } function handleNewIframe(iframe) { if (!config.lazyIframes) return; // 跳过已处理或特殊iframe(含有data-no-lazy属性) if (iframe.hasAttribute('data-no-lazy') || iframe.hasAttribute('data-lazy-loaded')) return; // 跳过srcdoc iframe (内容内联) if (iframe.hasAttribute('srcdoc')) return; setupIframeLazyLoading(iframe); } function initIframeObserver() { if (iframeIntersectionObserver) iframeIntersectionObserver.disconnect(); iframeIntersectionObserver = new IntersectionObserver((entries) => { for (const entry of entries) { if (entry.isIntersecting) { loadIframe(entry.target); } } }, { rootMargin: '200px' }); // 提前200px加载 // 处理已存在的iframe document.querySelectorAll('iframe:not([data-iframe-lazy]):not([data-lazy-loaded])').forEach(handleNewIframe); // 监听新添加的iframe if (iframeObserver) iframeObserver.disconnect(); iframeObserver = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'IFRAME') { handleNewIframe(node); } else if (node.querySelectorAll) { node.querySelectorAll('iframe:not([data-iframe-lazy]):not([data-lazy-loaded])').forEach(handleNewIframe); } } }); } } }); iframeObserver.observe(document.documentElement, { childList: true, subtree: true }); } function destroyIframeLazyLoad() { if (iframeIntersectionObserver) { iframeIntersectionObserver.disconnect(); iframeIntersectionObserver = null; } if (iframeObserver) { iframeObserver.disconnect(); iframeObserver = null; } // 恢复所有懒加载iframe的原始src document.querySelectorAll('iframe[data-iframe-lazy]').forEach(iframe => { const dataSrc = iframe.getAttribute('data-src'); if (dataSrc) { iframe.src = dataSrc; iframe.removeAttribute('data-src'); iframe.removeAttribute('data-iframe-lazy'); } }); iframesToLazy.clear(); } function toggleLazyIframes(enable) { if (enable) { initIframeObserver(); } else { destroyIframeLazyLoad(); } } // ---------- 初始化应用所有优化 ---------- function init() { // 根据配置应用各个模块 toggleAnimations(config.disableAnimations); toggleLazyLoad(config.lazyLoadImages); toggleTrackerBlocking(config.blockTrackers); toggleConsoleSilence(config.silenceConsole); toggleVideoOptimization(config.videoOptimization); toggleLazyIframes(config.lazyIframes); refreshMenuCommands(); } // 等待DOM准备就绪后开始处理图片(懒加载需要DOM) if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();