Universal Browser & Script Governor

Unified media optimization and adaptive network scheduling layer using fixed-rate batching for smoother performance and reduced DOM/network spikes.

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

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

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Advertisement:

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

Advertisement:

// ==UserScript==
// @name         Universal Browser & Script Governor
// @namespace    ultralean.universal.browser.script.stability
// @version      1.5.2
// @description  Unified media optimization and adaptive network scheduling layer using fixed-rate batching for smoother performance and reduced DOM/network spikes.
// @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;

	function netDelay() {
		const pressure = queue.length;
		let d = netConfig.baseDelay;

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

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

	/* =========================================================
	   🎥 MEDIA LAYER — HINT-ONLY OPTIMIZER
	========================================================= */

	const tracked = new WeakSet();

	function applyVideoHints(video) {
		if (!video || tracked.has(video)) return;
		tracked.add(video);

		// Preload strategy
		video.preload = video.hasAttribute("autoplay") ? "auto" : "metadata";

		// Inline playback stability
		video.playsInline = true;

		// Async decoding improves responsiveness
		video.decoding = "async";

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

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

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

		// Visibility tracking only
		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?.tagName === "VIDEO") {
				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]);
			}
		}
	}

	/* =========================================================
	   🌙 FIXED-RATE MUTATION BATCHING (80ms SINGLE SCHEDULER)
	========================================================= */

	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, 80);
	}

	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
	});

	/* initial scan */
	document.querySelectorAll("video").forEach(applyVideoHints);

})();