// ==UserScript== // @name Web Comprehensive Optimization Script(web综合优化脚本) // @namespace http://tampermonkey.net/ // @version 2.4 // @description Optimize non-first screen CSS, hardware acceleration, event throttling, debouncing, and more. // @author KiwiFruit // @match *://*/* // @grant none // @license MIT // @downloadURL https://update.greasyfork.icu/scripts/529387/Web%20Comprehensive%20Optimization%20Script%EF%BC%88web%E7%BB%BC%E5%90%88%E4%BC%98%E5%8C%96%E8%84%9A%E6%9C%AC%EF%BC%89.user.js // @updateURL https://update.greasyfork.icu/scripts/529387/Web%20Comprehensive%20Optimization%20Script%EF%BC%88web%E7%BB%BC%E5%90%88%E4%BC%98%E5%8C%96%E8%84%9A%E6%9C%AC%EF%BC%89.meta.js // ==/UserScript== (function() { 'use strict'; // 工具函数:事件节流 const throttle = (func, delay) => { let lastCall = 0; return function(...args) { const now = new Date().getTime(); if (now - lastCall >= delay) { lastCall = now; func.apply(this, args); } }; }; // 工具函数:防抖 const debounce = (func, delay) => { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); }; }; // 定义 calculateRootMargin 在最前面 const calculateRootMargin = () => { const windowHeight = window.innerHeight; const marginBottom = Math.max(0, windowHeight * 0.1); // 例如,取窗口高度的10% return `0px 0px ${marginBottom}px 0px`; }; // 模块:加载外部资源 const loadResource = (url, type) => new Promise((resolve, reject) => { const element = document.createElement(type === 'script' ? 'script' : 'link'); if (type === 'script') { element.src = url; } else { element.rel = 'stylesheet'; element.href = url; } element.onload = resolve; element.onerror = () => reject(new Error(`${type} loading failed: ${url}`)); document.head.appendChild(element); }); const loadScript = url => loadResource(url, 'script'); const loadStylesheet = href => loadResource(href, 'stylesheet'); // 模块:硬件加速 const initHardwareAcceleration = () => { const className = 'enable-hardware-acceleration'; const styleSheet = ` .${className} { transform: translateZ(0) !important; will-change: transform !important; }`; const styleElement = document.createElement('style'); styleElement.type = 'text/css'; styleElement.appendChild(document.createTextNode(styleSheet)); document.head.appendChild(styleElement); const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add(className); } else { entry.target.classList.remove(className); } }); }, { rootMargin: calculateRootMargin(), threshold: 0 }); return { observer }; }; // 模块:非首屏CSS懒加载 const initializeNonFirstScreenCssLazyLoading = async () => { document.querySelectorAll('.lazy-css').forEach(async (element) => { const href = element.getAttribute('data-lazy-css'); if (href) { try { await loadStylesheet(href); element.parentElement.removeChild(element); } catch (error) { console.error('Failed to load lazy CSS:', error); } } }); }; // DOM 变化监听模块 let mutationObserver; const observeDomChanges = () => { mutationObserver = new MutationObserver(throttle(mutations => { mutations.forEach(mutation => { mutation.addedNodes.forEach(node => { if (node.nodeType === 1) { handleNode(node); } }); }); }, 100)); // 增加节流,每100ms最多触发一次 // 开始观察 body 的子节点变化 mutationObserver.observe(document.body, { childList: true, subtree: true }); }; // 清理 DOM 变化观察器 const cleanupMutationObserver = () => { if (mutationObserver) { mutationObserver.disconnect(); mutationObserver = null; } }; // 处理新增的 DOM 节点 const handleNode = (node) => { if (node.classList.contains('lazy-css') && node.hasAttribute('data-lazy-css')) { const href = node.getAttribute('data-lazy-css'); loadStylesheet(href) .then(() => { if (node.parentElement) { node.parentElement.removeChild(node); } }) .catch(error => console.error('Failed to load lazy CSS:', error)); } }; // 动态生成首屏CSS资源 const generateCriticalCssUrls = () => { const hostname = window.location.hostname; // 获取当前域名 const criticalCssUrls = []; // 根据域名动态生成首屏CSS路径 if (hostname.includes('example.com')) { criticalCssUrls.push('/styles/example-critical.css'); // 替换为实际路径 } else if (hostname.includes('anotherwebsite.com')) { criticalCssUrls.push('/styles/anotherwebsite-critical.css'); // 替换为实际路径 } else { // 默认加载一个通用的首屏CSS文件 criticalCssUrls.push('/styles/default-critical.css'); // 替换为实际路径 } return criticalCssUrls.map(cssPath => `${window.location.origin}${cssPath}`); }; // 初始化示例 const initialize = async () => { if (!window.IntersectionObserver || !window.ResizeObserver) { console.warn('Your browser does not support some required features.'); return; } // 动态生成首屏CSS资源并优先加载 const criticalCssUrls = generateCriticalCssUrls(); // 并行加载首屏CSS资源 await Promise.all(criticalCssUrls.map(href => loadStylesheet(href))); // 初始化其他模块 initHardwareAcceleration(); await initializeNonFirstScreenCssLazyLoading(); // 监听 DOM 变化 observeDomChanges(); // 示例:添加滚动事件节流 window.addEventListener('scroll', throttle(() => { console.log('Scroll event triggered (throttled)'); }, 200)); // 示例:添加窗口调整大小事件防抖 window.addEventListener('resize', debounce(() => { console.log('Resize event triggered (debounced)'); }, 300)); }; // 页面卸载时清理资源 const cleanup = () => { cleanupMutationObserver(); }; // 页面加载完成后初始化 document.addEventListener("DOMContentLoaded", () => { initialize().catch(console.error); }); // 页面卸载时清理 window.addEventListener("beforeunload", () => { cleanup(); }); })();