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.

As of 2025-01-26. See the latest version.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==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();
    });
})();