You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

preloadImage.web.ts 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { isIconUrl } from './functions';
  2. /**
  3. * Tries to preload an image.
  4. *
  5. * @param {string | Object} src - Source of the avatar.
  6. * @param {boolean} useCORS - Whether to use CORS or not.
  7. * @param {boolean} tryOnce - If true we try to load the image only using the specified CORS mode. Otherwise both modes
  8. * (CORS and no CORS) will be used to load the image if the first attempt fails.
  9. * @returns {Promise}
  10. */
  11. export function preloadImage(
  12. src: string,
  13. useCORS = false,
  14. tryOnce = false
  15. ): Promise<{ isUsingCORS?: boolean; src: string | Object; }> {
  16. if (isIconUrl(src)) {
  17. return Promise.resolve({ src });
  18. }
  19. return new Promise((resolve, reject) => {
  20. const image = document.createElement('img');
  21. if (useCORS) {
  22. image.setAttribute('crossOrigin', '');
  23. }
  24. image.onload = () => resolve({
  25. src,
  26. isUsingCORS: useCORS
  27. });
  28. image.onerror = error => {
  29. if (tryOnce) {
  30. reject(error);
  31. } else {
  32. preloadImage(src, !useCORS, true)
  33. .then(resolve)
  34. .catch(reject);
  35. }
  36. };
  37. image.referrerPolicy = 'no-referrer';
  38. image.src = src;
  39. });
  40. }