Universal Browser & Script Governor

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

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

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

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

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

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

Advertisement:

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

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

})();