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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // 命名空间封装
    const WebOptimization = (function() {
        // 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(new Error('Script loading failed'));
                    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(new Error('Stylesheet loading failed'));
                    document.head.appendChild(link);
                });
            }
        };

        // Module: Hardware Acceleration
        const HardwareAcceleration = (() => {
            const className = 'enable-hardware-acceleration';
            const styleSheet = `
                .${className} {
                    transform: translateZ(0) !important; /* 使用 !important 提高样式优先级 */
                    will-change: transform !important;
                }
            `;
            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() {
                Loader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js')
                    .then(() => {
                        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.');
                        }
                    })
                    .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))
                            .catch(error => console.error('Failed to load lazy CSS:', error));
                    }
                });
            },

            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 = {
            throttle(func, wait) {
                let timeoutId = null;
                return function(...args) {
                    if (!timeoutId) {
                        timeoutId = setTimeout(() => {
                            func.apply(this, args);
                            timeoutId = null;
                        }, wait);
                    }
                };
            },

            handleScroll() {
                const throttledScrollHandler = this.throttle(() => {
                    console.log('Scroll event triggered');
                }, 100);

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

        // 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))
                                    .catch(error => console.error('Failed to load lazy CSS:', error));
                            } 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);
        });
    })(); // 封装模块,避免全局变量污染
})();