From 90d5b48845661ce99a204354f93fbbbc7a19f100 Mon Sep 17 00:00:00 2001 From: Albin Larsson Date: Tue, 15 May 2018 04:23:27 +0200 Subject: [PATCH] Add async method to utils for loading/checking images --- src/js/utils.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/js/utils.js b/src/js/utils.js index ebfb9c96..0cd332dd 100644 --- a/src/js/utils.js +++ b/src/js/utils.js @@ -119,6 +119,21 @@ const utils = { }); }, + // Load image avoiding xhr/fetch CORS issues + // Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded. + // By default it checks if it is at least 1px, but you can add a second argument to change this. + loadImage(src, minWidth = 1) { + return new Promise((resolve, reject) => { + const image = new Image(); + const handler = () => { + delete image.onload; + delete image.onerror; + (image.naturalWidth >= minWidth ? resolve : reject)(image); + }; + Object.assign(image, {onload: handler, onerror: handler, src}); + }); + }, + // Load an external script loadScript(url) { return new Promise((resolve, reject) => {