2019-06-26 14:08:23 +00:00
|
|
|
|
2019-07-16 10:23:01 +00:00
|
|
|
import { isIconUrl } from './functions';
|
|
|
|
|
2019-06-26 14:08:23 +00:00
|
|
|
/**
|
|
|
|
* Tries to preload an image.
|
|
|
|
*
|
2019-08-30 16:39:06 +00:00
|
|
|
* @param {string | Object} src - Source of the avatar.
|
2021-12-17 00:16:24 +00: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 07:10:08 +00:00
|
|
|
* (CORS and no CORS) will be used to load the image if the first attempt fails.
|
2019-06-26 14:08:23 +00:00
|
|
|
* @returns {Promise}
|
|
|
|
*/
|
2021-12-17 00:16:24 +00:00
|
|
|
export function preloadImage(
|
|
|
|
src: string | Object,
|
2023-02-02 11:12:31 +00:00
|
|
|
useCORS = false,
|
|
|
|
tryOnce = false
|
|
|
|
): Promise<{ isUsingCORS?: boolean; src: string | Object; }> {
|
2019-07-16 10:23:01 +00:00
|
|
|
if (isIconUrl(src)) {
|
2021-12-17 00:16:24 +00:00
|
|
|
return Promise.resolve({ src });
|
2019-07-16 10:23:01 +00:00
|
|
|
}
|
|
|
|
|
2019-06-26 14:08:23 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2021-02-10 09:24:04 +00:00
|
|
|
const image = document.createElement('img');
|
|
|
|
|
2021-12-17 00:16:24 +00:00
|
|
|
if (useCORS) {
|
2021-11-30 21:03:50 +00:00
|
|
|
image.setAttribute('crossOrigin', '');
|
|
|
|
}
|
2021-12-17 00:16:24 +00: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 09:24:04 +00:00
|
|
|
|
|
|
|
image.referrerPolicy = 'no-referrer';
|
2023-02-02 11:12:31 +00:00
|
|
|
|
|
|
|
// @ts-ignore
|
2021-02-10 09:24:04 +00:00
|
|
|
image.src = src;
|
2019-06-26 14:08:23 +00:00
|
|
|
});
|
|
|
|
}
|