Enhanced Faster Webpage Loading with Pjax

Preload subsequent pages, lazy load images and videos, and use Pjax for faster webpage loading with robust error handling and fallback navigation. Ensures no interference with other scripts enhancing media elements.

当前为 2025-01-26 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Enhanced Faster Webpage Loading with Pjax
// @namespace    http://tampermonkey.net/
// @version      2.2
// @description  Preload subsequent pages, lazy load images and videos, and use Pjax for faster webpage loading with robust error handling and fallback navigation. Ensures no interference with other scripts enhancing media elements.
// @author       Tae
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    // Utility: Lazy load elements
    function setupLazyLoading() {
        const lazyElements = Array.from(document.querySelectorAll("img.lazy, video.lazy, iframe.lazy:not([src])"));

        function loadLazyElement(el) {
            if (!el.dataset.src) return;

            if (!el.src) {
                el.src = el.dataset.src;
                if (el.tagName === "VIDEO") el.load();
            }
            el.classList.remove("lazy");
        }

        if ("IntersectionObserver" in window) {
            const observer = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        loadLazyElement(entry.target);
                        observer.unobserve(entry.target);
                    }
                });
            });

            lazyElements.forEach(el => observer.observe(el));
        } else {
            const lazyLoadFallback = () => {
                lazyElements.forEach((el, index) => {
                    if (
                        el.getBoundingClientRect().top < window.innerHeight &&
                        el.getBoundingClientRect().bottom > 0 &&
                        getComputedStyle(el).display !== "none"
                    ) {
                        loadLazyElement(el);
                        lazyElements.splice(index, 1);
                    }
                });

                if (lazyElements.length === 0) {
                    document.removeEventListener("scroll", lazyLoadFallback);
                    window.removeEventListener("resize", lazyLoadFallback);
                    window.removeEventListener("orientationchange", lazyLoadFallback);
                }
            };

            document.addEventListener("scroll", lazyLoadFallback);
            window.addEventListener("resize", lazyLoadFallback);
            window.addEventListener("orientationchange", lazyLoadFallback);
        }
    }

    // Utility: Prefetch links on hover
    function setupLinkPrefetching() {
        const prefetchedLinks = new Set();

        document.addEventListener("mouseover", event => {
            const link = event.target.closest("a[href]");
            if (link && !link.target && !link.rel.includes("nofollow") && !prefetchedLinks.has(link.href)) {
                const href = link.href;
                if (/^https?:\/\//.test(href) && !href.includes("#")) {
                    const prefetch = document.createElement("link");
                    prefetch.rel = "prefetch";
                    prefetch.href = href;
                    document.head.appendChild(prefetch);
                    prefetchedLinks.add(href);
                }
            }
        });
    }

    // Utility: Initialize Pjax
    function initializePjax() {
        if (typeof Pjax === "undefined") {
            const script = document.createElement("script");
            script.src = "https://cdnjs.cloudflare.com/ajax/libs/pjax/0.2.8/pjax.min.js";
            script.onload = setupPjax;
            document.head.appendChild(script);
        } else {
            setupPjax();
        }
    }

    function setupPjax() {
        const pjax = new Pjax({
            elements: "a[href]:not([target]):not([data-pjax-disabled])",
            selectors: ["title", ".content"],
            cacheBust: true,
        });

        document.addEventListener("pjax:send", () => console.log("Pjax: Request sent"));
        document.addEventListener("pjax:complete", () => {
            console.log("Pjax: Request complete");
            setupLazyLoading(); // Reinitialize lazy loading
        });
        document.addEventListener("pjax:error", event => {
            console.error("Pjax: Error occurred", event);
            if (event.request && event.request.responseURL) {
                window.location.href = event.request.responseURL;
            } else {
                console.warn("Fallback to standard navigation.");
            }
        });
    }

    // Initialize everything
    document.addEventListener("DOMContentLoaded", () => {
        setupLazyLoading();
        setupLinkPrefetching();
        initializePjax();
    });
})();