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.

Від 13.03.2025. Дивіться остання версія.

// ==UserScript==
// @name         Web Comprehensive Optimization Script(web综合优化脚本)
// @namespace    http://tampermonkey.net/
// @version      1.6
// @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';

    // Module: Load external resources
    const Loader = {
        loadScript(url) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = url;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        },
        loadStylesheet(href) {
            return new Promise((resolve, reject) => {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = href;
                link.onload = resolve;
                link.onerror = reject;
                document.head.appendChild(link);
            });
        }
    };

    // Module: Hardware Acceleration
    const HardwareAcceleration = (() => {
        const className = 'enable-hardware-acceleration';
        const styleSheet = `
            .${className} {
                transform: translateZ(0);
                will-change: transform;
            }
        `;
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add(className);
                } else {
                    entry.target.classList.remove(className);
                }
            });
        }, { rootMargin: '0px', threshold: 0 });

        function init() {
            const styleElement = document.createElement('style');
            styleElement.type = 'text/css';
            styleElement.appendChild(document.createTextNode(styleSheet));
            document.head.appendChild(styleElement);
        }

        return {
            init,
            observe(element) {
                observer.observe(element);
            }
        };
    })();

    // Module: Lazy Loading
    const LazyLoading = {
        initializeImageLazyLoading() {
            Loader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js').then(() => {
                const observer = lozad();
                observer.observe();
            });
        },
        initializeNonFirstScreenCssLazyLoading() {
            const elements = document.querySelectorAll('.lazy-css');
            elements.forEach(element => {
                const href = element.getAttribute('data-lazy-css');
                if (href) {
                    Loader.loadStylesheet(href).then(() => {
                        element.parentElement.removeChild(element);
                    });
                }
            });
        },
        initializeMediaPlayback() {
            const mediaElements = document.querySelectorAll('audio, video');
            mediaElements.forEach(element => {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            element.play();
                        } else {
                            element.pause();
                        }
                    });
                }, { rootMargin: '0px', threshold: 0 });
                observer.observe(element);
            });
        }
    };

    // Module: Event Handling
    const Events = {
            /**
         * 节流函数:限制某个函数在一定时间内的调用频率。
         * @param {Function} func - 需要节流的函数
         * @param {number} wait - 等待的时间间隔,单位为毫秒
         * @returns {Function} 返回一个经过节流处理的新函数
         */
        throttle(func, wait) {
            let timeoutId = null;
            return function(...args) {
                if (!timeoutId) {
                    timeoutId = setTimeout(() => {
                        func.apply(this, args);
                        timeoutId = null; // 清除定时器ID,允许下一次执行
                    }, wait);
                }
            };
        },

        /**
         * 初始化滚动事件监听,并应用节流处理。
         */
        handleScroll() {
            const throttledScrollHandler = this.throttle(() => {
                // 执行与滚动相关的逻辑
                console.log('Scroll event triggered');
            }, 100);

            window.addEventListener('scroll', throttledScrollHandler.bind(this));
        }
    };

    // Initialization 示例
    document.addEventListener("DOMContentLoaded", function() {
        // 初始化事件模块
        Events.handleScroll();
    });

    // Initialization
    document.addEventListener("DOMContentLoaded", function() {
        // Initialize modules
        HardwareAcceleration.init();
        LazyLoading.initializeImageLazyLoading();
        LazyLoading.initializeNonFirstScreenCssLazyLoading();
        LazyLoading.initializeMediaPlayback();
        Events.handleScroll();

        // Listen for DOM changes
        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: '0px', threshold: 0 });
                            observer.observe(node);
                        } else if (node.classList.contains('lazy-css') && node.hasAttribute('data-lazy-css')) {
                            const href = node.getAttribute('data-lazy-css');
                            Loader.loadStylesheet(href).then(() => {
                                node.parentElement.removeChild(node);
                            });
                        } else if (node.matches('.target-element')) {
                            HardwareAcceleration.observe(node);
                        }
                    }
                });
            });
        });
        mutationObserver.observe(document.body, { childList: true, subtree: true });

        // Resize Observer
        const resizeObserver = new ResizeObserver(() => {
            requestAnimationFrame(() => {
                // Reapply hardware acceleration or other necessary adjustments
            });
        });
        resizeObserver.observe(document.body);
    });
})();