Old Reddit Layout: Restore Subreddit Subscriber Count

Fetches and displays the subreddit subscriber count on old Reddit layout (old.reddit.com and www.reddit.com with old layout) below the subreddit title.

// ==UserScript==
// @name         Old Reddit Layout: Restore Subreddit Subscriber Count
// @namespace    https://greatest.deepsurf.us/en/users/181401-shajirr
// @version      2025.09.25
// @description  Fetches and displays the subreddit subscriber count on old Reddit layout (old.reddit.com and www.reddit.com with old layout) below the subreddit title.
// @author       Shajirr
// @match        https://old.reddit.com/r/*
// @match        https://www.reddit.com/r/*
// @icon         https://www.redditstatic.com/desktop2x/img/favicon/favicon-32x32.png
// @grant        none
// @noframes
// @license      GNU GPLv3
// ==/UserScript==

(function() {
    'use strict';

    // Function to fetch and display subscriber count
    function loadSubscriberCount() {
        // Get the current subreddit name from the URL
        const subredditMatch = window.location.pathname.match(/^\/r\/([a-z0-9_-]+)\//i);
        if (!subredditMatch) return;

        const subreddit = subredditMatch[1];
        const apiUrl = `https://www.reddit.com/r/${subreddit}/about.json`;

        // Fetch the data
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                if (data.data && typeof data.data.subscribers === 'number') {
                    const count = data.data.subscribers.toLocaleString(); // Format with commas (e.g., 1,234,567)
                    updateSidebar(count);
                } else {
                    console.error('Failed to fetch subscribers:', data);
                }
            })
            .catch(error => {
                console.error('Error fetching subreddit data:', error);
            });
    }

    // Function to update the sidebar with the count
    function updateSidebar(count) {
        // Target the titlebox in the sidebar
        const titlebox = document.querySelector('.side .spacer .titlebox');
        if (!titlebox) return;

        // Check for existing subscribers element to avoid duplicates
        let subscriberElement = document.querySelector('.side .subscribers');

        if (!subscriberElement) {
            // Create a new <p> element for the subscriber count
            subscriberElement = document.createElement('p');
            subscriberElement.className = 'subscribers';
            subscriberElement.style.margin = '5px 0'; // Mimic original spacing
            subscriberElement.style.fontWeight = 'bold'; // Mimic original bold style

            // Find the subreddit title (<h1 class="hover redditname">) to insert after
            const title = document.querySelector('.side .spacer .titlebox h1.redditname');
            const buttons = document.querySelector('.side .spacer .titlebox .subButtons');
            if (title && buttons) {
                // Insert after the title but before the buttons
                titlebox.insertBefore(subscriberElement, buttons);
            } else if (title) {
                // Fallback: insert after the title if buttons are missing
                title.parentNode.insertBefore(subscriberElement, title.nextSibling);
            } else {
                // Fallback: insert at the top of titlebox if title is missing
                titlebox.insertBefore(subscriberElement, titlebox.firstChild);
            }
        }

        // Update the text
        subscriberElement.innerHTML = `${count} subscribers`;
    }

    // Run on page load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', loadSubscriberCount);
    } else {
        loadSubscriberCount();
    }

    // Re-run on subreddit changes (e.g., infinite scroll or navigation)
    let lastSubreddit = null;
    const observer = new MutationObserver(() => {
        const currentSubreddit = window.location.pathname.match(/^\/r\/([a-z0-9_-]+)\//i)?.[1];
        if (currentSubreddit && currentSubreddit !== lastSubreddit) {
            lastSubreddit = currentSubreddit;
            // Small delay to let DOM settle
            setTimeout(loadSubscriberCount, 500);
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();