feat: implement priority yielding between audio and image loaders to optimize resource loading

This commit is contained in:
Tomáš Mládek 2025-07-27 21:52:20 +02:00
parent 33491dba3e
commit 10526f560f
2 changed files with 26 additions and 0 deletions

View file

@ -1,9 +1,13 @@
/**
* Global audio loading queue service to prevent hitting browser connection limits
* Will yield to image loading if images are queued
*/
import { hasQueuedImages } from "./ImageLoader";
// Configuration
const MAX_CONCURRENT_LOADS = 1;
const RETRY_DELAY_MS = 200; // Time to wait before retrying if yielding to images
// State
let activeLoads = 0;
@ -82,6 +86,14 @@ export function queueAudioForLoading(
* Process the next items in the queue if we have capacity
*/
function processQueue() {
// Check if there are any images being loaded or queued - yield to them if so
if (hasQueuedImages()) {
console.debug("[AudioLoader] Yielding to image loader, will retry later");
// Schedule a retry after a short delay
setTimeout(processQueue, RETRY_DELAY_MS);
return;
}
// Group queue items by src to avoid duplicate loads
const nextBatch: Record<
string,
@ -119,6 +131,12 @@ function processQueue() {
Object.entries(nextBatch).forEach(([src, handlers]) => {
loadAudio(src, handlers);
});
// If we have more items in the queue but didn't process them due to capacity limits,
// and no images are queued, schedule another processQueue call to check again soon
if (audioQueue.length > 0 && !hasQueuedImages()) {
setTimeout(processQueue, RETRY_DELAY_MS);
}
}
/**

View file

@ -12,6 +12,14 @@ const imageQueue: Array<{
onComplete: () => void;
}> = [];
/**
* Check if there are any images queued or actively loading
* Used by other loaders to prioritize image loading
*/
export function hasQueuedImages(): boolean {
return imageQueue.length > 0 || activeLoads > 0;
}
/**
* Queue an image for loading, respecting the global concurrent loading limit
*/