Reddit Old Infinite Scroll

Infinite scroll (autopagerize) for old.reddit.com. Prefetches early and ads a visible page note.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey, Greasemonkey или Violentmonkey.

Для установки этого скрипта вам необходимо установить расширение, такое как Tampermonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например Tampermonkey.

Чтобы установить этот скрипт, вы должны установить расширение — менеджер скриптов.

(у меня уже есть менеджер скриптов, дайте мне установить скрипт!)

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

(у меня уже есть менеджер стилей, дайте мне установить скрипт!)

// ==UserScript==
// @name         Reddit Old Infinite Scroll
// @namespace    https://github.com/BD9Max
// @version      1.0
// @description  Infinite scroll (autopagerize) for old.reddit.com. Prefetches early and ads a visible page note.
// @author       krbd9max
// @match        https://old.reddit.com/*
// @exclude      https://old.reddit.com/prefs*
// @exclude      https://old.reddit.com/message*
// @grant        none
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    let isLoading = false;
    let nextPageUrl = null;
    let pageCount = 1;

    // --- CONFIGURATION ---
    const TRIGGER_THRESHOLD = 1700; // pixel distance from bottom until prefetch
    const SEPARATOR_TEXT = "--- PAGE {n} ---";

    // CSS page divider
    const style = document.createElement('style');
    style.textContent = `
        .pager-separator {
            clear: both;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 40px 0;
            padding: 10px;
            font-family: verdana, arial, helvetica, sans-serif;
        }
        .pager-separator::before, .pager-separator::after {
            content: "";
            flex: 1;
            height: 1px;
            background: #cee3f8;
            margin: 0 20px;
        }
        .pager-note {
            color: #888;
            font-size: 10px;
            font-weight: bold;
            letter-spacing: 2px;
            text-transform: uppercase;
        }
        .nav-buttons { display: none !important; } /* Hides original next/prev buttons */
    `;
    document.head.appendChild(style);

    function getNextUrl() {
        const nextButton = document.querySelector('.next-button a');
        return nextButton ? nextButton.href : null;
    }

    function createSeparator(num) {
        const div = document.createElement('div');
        div.className = 'pager-separator';
        div.innerHTML = `<span class="pager-note">${SEPARATOR_TEXT.replace('{n}', num)}</span>`;
        return div;
    }

    async function loadNextPage() {
        if (isLoading) return;
        
        const url = nextPageUrl || getNextUrl();
        if (!url) return;

        isLoading = true;
        console.log("Loading next page:", url);

        try {
            const response = await fetch(url);
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            const siteTable = document.querySelector('#siteTable');
            const newPosts = doc.querySelectorAll('#siteTable > .thing');
            const nextBtn = doc.querySelector('.next-button a');

            if (newPosts.length > 0) {
                pageCount++;
                siteTable.appendChild(createSeparator(pageCount));

                newPosts.forEach(post => {
                    // Update rank numbers to continue the sequence
                    const rank = post.querySelector('.rank');
                    if (rank && rank.innerText) {
                        const currentMax = document.querySelectorAll('#siteTable > .thing').length;
                        rank.innerText = parseInt(rank.innerText) || '';
                    }
                    siteTable.appendChild(post);
                });

                // Update the URL for the next fetch
                nextPageUrl = nextBtn ? nextBtn.href : null;
                
                // Trigger any Reddit-native JS for the new elements (like expando buttons)
                if (window.reddit && window.reddit.setup_expandos) {
                    window.reddit.setup_expandos();
                }
            } else {
                nextPageUrl = null; // No more pages
            }
        } catch (err) {
            console.error("Error loading next page:", err);
        } finally {
            isLoading = false;
        }
    }

    // Scroll listener with throttle-like check
    window.addEventListener('scroll', () => {
        const scrollPos = window.innerHeight + window.pageYOffset;
        const pageHeight = document.documentElement.scrollHeight;

        // If we are within TRIGGER_THRESHOLD of the bottom, load the next page
        if (scrollPos >= pageHeight - TRIGGER_THRESHOLD) {
            loadNextPage();
        }
    });

    // Initial check in case the page is very short
    if (document.documentElement.scrollHeight <= window.innerHeight + TRIGGER_THRESHOLD) {
        loadNextPage();
    }
})();