您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

preloadImage.web.ts 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 | Object,
  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. // @ts-ignore
  39. image.src = src;
  40. });
  41. }