2019-06-26 16:08:23 +02:00
|
|
|
|
|
|
|
|
// @flow
|
|
|
|
|
|
2019-07-16 11:23:01 +01:00
|
|
|
import { isIconUrl } from './functions';
|
|
|
|
|
|
2019-06-26 16:08:23 +02:00
|
|
|
/**
|
|
|
|
|
* Tries to preload an image.
|
|
|
|
|
*
|
2019-08-30 18:39:06 +02:00
|
|
|
* @param {string | Object} src - Source of the avatar.
|
2021-12-16 18:16:24 -06:00
|
|
|
* @param {boolean} useCORS - Whether to use CORS or not.
|
|
|
|
|
* @param {boolean} tryOnce - If true we try to load the image only using the specified CORS mode. Otherwise both modes
|
2022-07-14 03:10:08 -04:00
|
|
|
* (CORS and no CORS) will be used to load the image if the first attempt fails.
|
2019-06-26 16:08:23 +02:00
|
|
|
* @returns {Promise}
|
|
|
|
|
*/
|
2021-12-16 18:16:24 -06:00
|
|
|
export function preloadImage(
|
|
|
|
|
src: string | Object,
|
|
|
|
|
useCORS: ?boolean = false,
|
|
|
|
|
tryOnce: ?boolean = false
|
|
|
|
|
): Promise<Object> {
|
2019-07-16 11:23:01 +01:00
|
|
|
if (isIconUrl(src)) {
|
2021-12-16 18:16:24 -06:00
|
|
|
return Promise.resolve({ src });
|
2019-07-16 11:23:01 +01:00
|
|
|
}
|
|
|
|
|
|
2019-06-26 16:08:23 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
2021-02-10 10:24:04 +01:00
|
|
|
const image = document.createElement('img');
|
|
|
|
|
|
2021-12-16 18:16:24 -06:00
|
|
|
if (useCORS) {
|
2021-11-30 15:03:50 -06:00
|
|
|
image.setAttribute('crossOrigin', '');
|
|
|
|
|
}
|
2021-12-16 18:16:24 -06:00
|
|
|
image.onload = () => resolve({
|
|
|
|
|
src,
|
|
|
|
|
isUsingCORS: useCORS
|
|
|
|
|
});
|
|
|
|
|
image.onerror = error => {
|
|
|
|
|
if (tryOnce) {
|
|
|
|
|
reject(error);
|
|
|
|
|
} else {
|
|
|
|
|
preloadImage(src, !useCORS, true)
|
|
|
|
|
.then(resolve)
|
|
|
|
|
.catch(reject);
|
|
|
|
|
}
|
|
|
|
|
};
|
2021-02-10 10:24:04 +01:00
|
|
|
|
|
|
|
|
// $FlowExpectedError
|
|
|
|
|
image.referrerPolicy = 'no-referrer';
|
|
|
|
|
image.src = src;
|
2019-06-26 16:08:23 +02:00
|
|
|
});
|
|
|
|
|
}
|