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.

Для установки этого скрипта вам необходимо установить расширение, такое как Tampermonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например 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);

})();