index.ts 658 B

123456789101112131415161718192021
  1. function loadingFailed(imgEl: HTMLImageElement) {
  2. return imgEl.complete && imgEl.naturalWidth === 0
  3. }
  4. document.querySelectorAll('[data-ol-fallback-image]').forEach(element => {
  5. if (!(element instanceof HTMLImageElement)) {
  6. // The sprinkle only applies to image elements.
  7. return
  8. }
  9. const imgEl = element as HTMLImageElement
  10. function showFallback() {
  11. imgEl.src = imgEl.getAttribute('data-ol-fallback-image')!
  12. }
  13. if (loadingFailed(imgEl)) {
  14. // The image loading failed before the sprinkle ran.
  15. showFallback()
  16. } else {
  17. // The image loading might fail in the future.
  18. imgEl.addEventListener('error', showFallback)
  19. }
  20. })