Web Comprehensive Optimization Script

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

// ==UserScript==
// @name         Web Comprehensive Optimization Script
// @namespace    http://tampermonkey.net/
// @version      1.9
// @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);
        });
    })(); // 封装模块,避免全局变量污染
})();