jiti-meet/react/features/base/participants/preloadImage.web.ts

48 lines
1.3 KiB
TypeScript
Raw Normal View History

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
* (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) => {
const image = document.createElement('img');
2021-12-17 00:16:24 +00:00
if (useCORS) {
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);
}
};
image.referrerPolicy = 'no-referrer';
2023-02-02 11:12:31 +00:00
// @ts-ignore
image.src = src;
2019-06-26 14:08:23 +00:00
});
}