Greasy Fork is available in English.

Remove Ads in Tieba

Remove advertisement elements using wildcard

// ==UserScript==
// @name         Remove Ads in Tieba
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Remove advertisement elements using wildcard
// @author       aspen138
// @match        *://tieba.baidu.com/p/*
// @match        *://tieba.baidu.com/*
// @icon         https://tb3.bdstatic.com/public/icon/favicon-v2.ico
// @grant        none
// @license      MIT
// ==/UserScript==



(function() {
    'use strict';

    // Combined selector for all ad elements
    const AD_SELECTORS = [
        '.fengchao-wrap-feed',
        '[id^="mediago-tb-pb-list-"]',
        '[id^="mediago-tb-frs-list-"]',
        '.mediago-ad-wrapper',
        '.mediago-ad',
        '.thread_item_box:has(.ec-tuiguang)'
    ].join(',');

    // Function to remove advertisement elements
    function removeAds() {
        // Single querySelectorAll call for all ad elements
        const ads = document.querySelectorAll(AD_SELECTORS);
        ads.forEach(element => element.remove());
    }

    // Run the function to remove ads initially
    removeAds();

    // Optimize observer by using a debounced function
    let timeout = null;
    const observer = new MutationObserver(() => {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(removeAds, 100);
    });

    // Start observing with optimized configuration
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
    });
})();