diff --git a/coroutines/src/jsMain/kotlin/dev.inmo.micro_utils.coroutines/ImagePreloading.kt b/coroutines/src/jsMain/kotlin/dev.inmo.micro_utils.coroutines/ImagePreloading.kt new file mode 100644 index 00000000000..06304f373b6 --- /dev/null +++ b/coroutines/src/jsMain/kotlin/dev.inmo.micro_utils.coroutines/ImagePreloading.kt @@ -0,0 +1,26 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import org.w3c.dom.Image + +suspend fun preloadImage(src: String): Image { + val image = Image() + image.src = src + + val job = Job() + + image.addEventListener("load", { + runCatching { job.complete() } + }) + + runCatchingSafely { + job.join() + }.onFailure { + if (it is CancellationException) { + image.src = "" + } + }.getOrThrow() + + return image +}