Web Comprehensive Optimization Script(web综合优化脚本)

Optimize non-first screen CSS and image lazy loading, hardware acceleration, script lazy loading, code splitting, caching strategy, event throttling, and more.

目前为 2025-03-22 提交的版本。查看 最新版本

// ==UserScript==
// @name         Web Comprehensive Optimization Script(web综合优化脚本)
// @namespace    http://tampermonkey.net/
// @version      2.3
// @description  Optimize non-first screen CSS and image lazy loading, hardware acceleration, script lazy loading, code splitting, caching strategy, event throttling, and more.
// @author       KiwiFruit
// @match        *://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 定义 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 };
    };

    // 模块:懒加载
    const initializeImageLazyLoading = async () => {
        const scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js';
        await loadScript(scriptUrl);
        if (typeof window.lozad === 'function') {
            const observer = window.lozad();
            observer.observe();
        } else {
            console.error('Lozad.js failed to load or did not expose the expected global function.');
        }
    };

    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);
                }
            }
        });
    };

    // 初始化示例
    const initialize = async () => {
        if (!window.IntersectionObserver || !window.ResizeObserver) {
            console.warn('Your browser does not support some required features.');
            return;
        }

        // 确保首屏所需的CSS资源被优先加载
        const criticalCssUrls = [
            'https://example.com/style1.css',
            'https://example.com/style2.css'
        ];
        criticalCssUrls.forEach(href => loadStylesheet(href));

        // 初始化其他模块
        initHardwareAcceleration();
        await initializeImageLazyLoading();
        await initializeNonFirstScreenCssLazyLoading();

        // 监听 DOM 变化
        const mutationObserver = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) {
                        if (node.tagName === 'IMG' && node.hasAttribute('data-src')) {
                            const observer = new IntersectionObserver((entries) => {
                                entries.forEach(entry => {
                                    if (entry.isIntersecting) {
                                        node.src = node.getAttribute('data-src');
                                        observer.unobserve(node);
                                    }
                                });
                            }, { rootMargin: calculateRootMargin(), threshold: 0 });
                            observer.observe(node);
                        } else if (node.classList.contains('lazy-css') && node.hasAttribute('data-lazy-css')) {
                            const href = node.getAttribute('data-lazy-css');
                            loadStylesheet(href)
                                .then(() => node.parentElement.removeChild(node))
                                .catch(error => console.error('Failed to load lazy CSS:', error));
                        }
                    }
                });
            });
        });
        mutationObserver.observe(document.body, { childList: true, subtree: true });
    };

    // 页面加载完成后初始化
    document.addEventListener("DOMContentLoaded", () => {
        initialize().catch(console.error);
    });
})();