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

49 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-06-26 14:08:23 +00:00
// @flow
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 atempt 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,
useCORS: ?boolean = false,
tryOnce: ?boolean = false
): Promise<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);
}
};
// $FlowExpectedError
image.referrerPolicy = 'no-referrer';
image.src = src;
2019-06-26 14:08:23 +00:00
});
}