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 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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();
    });
})();