web综合优化脚本(非首屏资源延迟加载与硬件加速)

优化非首屏CSS与图片延迟加载、硬件加速等功能。

当前为 2025-03-10 提交的版本,查看 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         web综合优化脚本(非首屏资源延迟加载与硬件加速)
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  优化非首屏CSS与图片延迟加载、硬件加速等功能。
// @author       KiwiFruit
// @match        *://*/*
// @grant        none
// @license MIT
// ==/UserScript==
(function() {
    'use strict';

    // 引入 lozad.js 库
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js';
    document.head.appendChild(script);

    // 定义硬件加速相关的CSS类
    const hardwareAccelerationClass = 'enable-hardware-acceleration';
    const styleSheet = `
        .${hardwareAccelerationClass} {
            transform: translateZ(0);
            will-change: transform;
        }
    `;
    const styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.appendChild(document.createTextNode(styleSheet));
    document.head.appendChild(styleElement);

    // 判断元素是否在视口内
    function isElementInViewport(el) {
        const rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }

    // 启用硬件加速
    function enableHardwareAccelerationForVisibleElements() {
        const targetElements = document.querySelectorAll('.target-element');
        targetElements.forEach(element => {
            if (isElementInViewport(element)) {
                element.classList.add(hardwareAccelerationClass);
            } else {
                element.classList.remove(hardwareAccelerationClass);
            }
        });
    }

    // 页面加载完成后执行的初始化逻辑
    window.addEventListener('DOMContentLoaded', (event) => {
        // 初始化 lozad.js 图片懒加载
        script.onload = () => {
            const observer = lozad(); // lazy loads elements with default selector as '.lozad'
            observer.observe();
        };

        // 初始化非首屏CSS懒加载
        const lazyCssElements = document.querySelectorAll('.lazy-css');
        lazyCssElements.forEach(element => {
            const cssHref = element.getAttribute('data-lazy-css');
            if (cssHref) {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = cssHref;
                document.head.appendChild(link);
                element.parentElement.removeChild(element); // 移除占位符元素
            }
        });

        // 监听滚动事件(使用节流)
        window.addEventListener('scroll', () => {
            requestIdleCallback(enableHardwareAccelerationForVisibleElements);
        });

        // 监听点击事件(使用防抖)
        document.addEventListener('click', () => {
            requestIdleCallback(enableHardwareAccelerationForVisibleElements);
        });

        // 监听媒体播放事件
        document.addEventListener('play', enableHardwareAccelerationForVisibleElements, true);

        // 监听图片加载事件
        document.addEventListener('load', enableHardwareAccelerationForVisibleElements, true);

        // 初始化检查一次
        enableHardwareAccelerationForVisibleElements();

        // MutationObserver监听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 = lozad(node); // lazy loads specific image
                            observer.observe();
                        } else if (node.classList.contains('lazy-css') && node.hasAttribute('data-lazy-css')) {
                            const cssHref = node.getAttribute('data-lazy-css');
                            const link = document.createElement('link');
                            link.rel = 'stylesheet';
                            link.href = cssHref;
                            document.head.appendChild(link);
                            node.parentElement.removeChild(node); // 移除占位符元素
                        } else if (node.matches('.target-element')) {
                            enableHardwareAccelerationForVisibleElements();
                        }
                    }
                });
            });
        });
        mutationObserver.observe(document.body, { childList: true, subtree: true });

        // ResizeObserver监控视口尺寸变化
        const resizeObserver = new ResizeObserver(() => {
            enableHardwareAccelerationForVisibleElements();
        });
        resizeObserver.observe(document.body);
    });
})();