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 기준 버전입니다. 최신 버전을 확인하세요.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

You will need to install an extension such as Tampermonkey to install this script.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 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();
    });
})();