Universal Browser & Script Governor

Unified media optimization and adaptive network scheduling layer that smooths playback performance, reduces DOM and network spikes, and improves overall browser stability without interfering with core site behavior.

ही स्क्रिप्ट इंस्टॉल करण्यासाठी तुम्हाला Tampermonkey, Greasemonkey किंवा Violentmonkey यासारखे एक्स्टेंशन इंस्टॉल करावे लागेल.

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

ही स्क्रिप्ट इंस्टॉल करण्यासाठी तुम्हाला Tampermonkey किंवा Violentmonkey यासारखे एक्स्टेंशन इंस्टॉल करावे लागेल..

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

ही स्क्रिप्ट इंस्टॉल करण्यासाठी तुम्हाला Tampermonkey यासारखे एक्स्टेंशन इंस्टॉल करावे लागेल..

ही स्क्रिप्ट इंस्टॉल करण्यासाठी तुम्हाला एक युझर स्क्रिप्ट व्यवस्थापक एक्स्टेंशन इंस्टॉल करावे लागेल.

(माझ्याकडे आधीच युझर स्क्रिप्ट व्यवस्थापक आहे, मला इंस्टॉल करू द्या!)

Advertisement:

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला Stylus सारखे एक्स्टेंशन इंस्टॉल करावे लागेल.

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला Stylus सारखे एक्स्टेंशन इंस्टॉल करावे लागेल.

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला Stylus सारखे एक्स्टेंशन इंस्टॉल करावे लागेल.

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला एक युझर स्टाईल व्यवस्थापक इंस्टॉल करावे लागेल.

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला एक युझर स्टाईल व्यवस्थापक इंस्टॉल करावे लागेल.

ही स्टाईल इंस्टॉल करण्यासाठी तुम्हाला एक युझर स्टाईल व्यवस्थापक इंस्टॉल करावे लागेल.

(माझ्याकडे आधीच युझर स्टाईल व्यवस्थापक आहे, मला इंस्टॉल करू द्या!)

Advertisement:

// ==UserScript==
// @name         Universal Browser & Script Governor
// @namespace    ultralean.universal.browser.script.stability
// @version      1.4
// @description  Unified media optimization and adaptive network scheduling layer that smooths playback performance, reduces DOM and network spikes, and improves overall browser stability without interfering with core site behavior.
// @author       Michael Stutesman
// @license      MIT
// @match        *://*/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @run-at       document-start
// ==/UserScript==

(() => {
	'use strict';

	/* ---------------- SINGLETON ---------------- */
	if (window.__UNIVERSAL_STABILITY_ENGINE__) return;
	window.__UNIVERSAL_STABILITY_ENGINE__ = true;

	/* =========================================================
	   🚫 PERSISTENT SITE EXCLUSIONS (GM STORAGE)
	========================================================= */

	const HOST = location.hostname.toLowerCase();
	const STORAGE_KEY = "ugb_excluded_sites";

	let excluded = GM_getValue(STORAGE_KEY, []);
	if (!Array.isArray(excluded)) excluded = [];

	function isExcludedSite() {
		for (let i = 0; i < excluded.length; i++) {
			const site = excluded[i];
			if (HOST === site || HOST.endsWith("." + site)) return true;
		}
		return false;
	}

	if (isExcludedSite()) return;

	GM_registerMenuCommand("🚫 Exclude this site", () => {
		if (!excluded.includes(HOST)) {
			excluded.push(HOST);
			GM_setValue(STORAGE_KEY, excluded);
		}
		location.reload();
	});

	GM_registerMenuCommand("🔄 Clear exclusions", () => {
		if (!confirm("Clear all excluded sites?")) return;
		GM_setValue(STORAGE_KEY, []);
		location.reload();
	});

	/* =========================================================
	   🌐 NETWORK LAYER — SPIKE GOVERNOR
	========================================================= */

	const netConfig = {
		baseDelay: 1,
		maxConcurrent: 7,
		burstThreshold: 14,
		burstDelay: 9
	};

	const queue = [];
	let active = 0;
	let lastRun = 0;

	function netDelay() {
		const pressure = queue.length;

		let d = netConfig.baseDelay;

		if (pressure >= netConfig.burstThreshold) {
			d += netConfig.burstDelay;
		}

		if (performance.now() - lastRun < 500) {
			d += 10;
		}

		lastRun = performance.now();
		return d;
	}

	function runQueue() {
		if (active >= netConfig.maxConcurrent) return;
		if (!queue.length) return;

		active++;

		const job = queue.shift();

		setTimeout(async () => {
			try {
				const res = await job.exec();
				job.resolve(res);
			} catch (e) {
				job.reject(e);
			}

			active--;
			runQueue();
		}, netDelay());
	}

	function enqueue(exec) {
		return new Promise((resolve, reject) => {
			queue.push({ exec, resolve, reject });
			runQueue();
		});
	}

	/* ---- Fetch Hook ---- */
	const _fetch = window.fetch;

	window.fetch = (...args) =>
		enqueue(() => _fetch(...args));

	/* ---- XHR Hook ---- */
	const XHR = XMLHttpRequest;

	function WrappedXHR() {
		const xhr = new XHR();

		const _open = xhr.open;
		const _send = xhr.send;

		let body;

		xhr.open = function () {
			return _open.apply(xhr, arguments);
		};

		xhr.send = function (b) {
			body = b;

			return enqueue(() => new Promise((resolve, reject) => {
				xhr.onload = () => resolve(xhr);
				xhr.onerror = () => reject(xhr);
				_send.call(xhr, body);
			}));
		};

		return xhr;
	}

	window.XMLHttpRequest = WrappedXHR;

	/* =========================================================
	   🎥 MEDIA LAYER — OPTIMIZER
	========================================================= */

	const mediaConfig = {
		maxVideosTracked: 60
	};

	const tracked = new WeakSet();
	let videoCount = 0;

	function applyVideoHints(video) {
		if (!video || tracked.has(video)) return;
		if (videoCount >= mediaConfig.maxVideosTracked) return;

		tracked.add(video);
		videoCount++;

		video.preload = video.hasAttribute("autoplay") ? "auto" : "metadata";
		video.playsInline = true;

		video.disablePictureInPicture = true;
		video.disableRemotePlayback = true;

		video.decoding = "async";

		if (navigator.connection?.saveData) {
			video.preload = "none";
		}

		if ("fetchPriority" in video) {
			video.fetchPriority = video.hasAttribute("autoplay") ? "high" : "low";
		}

		video.style.contentVisibility = "auto";
		video.style.containIntrinsicSize = "480px 270px";

		if (!video.__OBS__) {
			video.__OBS__ = true;
			observer.observe(video);
		}
	}

	const observer = new IntersectionObserver((entries) => {
		for (const e of entries) {
			const v = e.target;
			if (!v || v.tagName !== "VIDEO") continue;

			v.dataset.visible = e.isIntersecting ? "1" : "0";
		}
	}, {
		rootMargin: "300px"
	});

	function processNode(node) {
		if (!node) return;

		if (node.tagName === "VIDEO") {
			applyVideoHints(node);
			return;
		}

		if (node.querySelectorAll) {
			const vids = node.querySelectorAll("video");
			for (let i = 0; i < vids.length; i++) {
				applyVideoHints(vids[i]);
			}
		}
	}

	/* ---- Mutation batching (media only) ---- */
	let dirty = new Set();
	let scheduled = false;

	function flush() {
		scheduled = false;

		for (const n of dirty) {
			processNode(n);
		}

		dirty.clear();
	}

	function schedule() {
		if (scheduled) return;
		scheduled = true;
		setTimeout(flush, 120);
	}

	new MutationObserver(muts => {
		for (const m of muts) {
			for (const n of m.addedNodes) {
				dirty.add(n);
			}
		}
		schedule();
	}).observe(document.documentElement, {
		childList: true,
		subtree: true
	});

	document.querySelectorAll("video").forEach(applyVideoHints);

})();