Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

preloadImage.web.js 1.3KB

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