Greasy Fork

Greasy Fork is available in English.

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-14 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Web Comprehensive Optimization Script(web综合优化脚本)
// @namespace    http://tampermonkey.net/
// @version      1.8
// @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 0px ${rootMarginBottom} 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() {
            // 动态加载 lozad.js 脚本,并确保它已成功加载后再使用
            Loader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js').then(() => {
                if (typeof window.lozad === 'function') { // 检查 lozad 是否可用
                    const observer = window.lozad(); // 使用 window.lozad 以确保访问全局对象
                    observer.observe();
                } else {
                    console.error('Lozad.js failed to load or did not expose the expected global function.');
                }
            }).catch(error => {
                console.error('Failed to load Lozad script:', error);
            });
        },

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

    // Initialization 示例
    document.addEventListener("DOMContentLoaded", function() {
        // 初始化懒加载模块
        LazyLoading.initializeImageLazyLoading();
    });

    // 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 0px ${rootMarginBottom} 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);
    });
})();