Search code examples
javascriptreactjsgoogle-chromesafari

onLoad event of <img /> tag does't fire on initial page access


Consider following component

import React from 'react';

function Image() {
  function onLoad() {
    console.log("Loaded...")
  }

  return (
      <img
        src="http://..."
        onLoad={onLoad}
        decoding="async"
      />
  );
}

export default Image;

For some reason onLoad event isn't firing consistently i.e. when I initially load the page and refresh it it is not triggered, but when I mount component interactively in react i.e without page load it is triggered.

I played around with removing decoding="async" and adding onError handler to see if those gave more info, but behaviour didn't change.

I see this same behaviour on macOS safari and chrome browsers.

EDIT: In cases where it doesn't work image is not loaded at all


Solution

  • I figured out how to make it work in my case. I guess onLoad event wasn't executing because image was already loaded, so I altered my code to the following and it works as expected now

    import React, { useRef, useEffect } from 'react';
    
    function Image() {
      const imgRef = useRef<HTMLImageElement>(null);
    
      function onLoad() {
        console.log("Loaded...")
      }
    
      useEffect(() => {
       if (imgRef.current?.complete) {
        onLoad();
       }
      }, []);
    
      return (
          <img
            ref={imgRef}
            src="http://..."
            onLoad={onLoad}
            decoding="async"
          />
      );
    }
    
    export default Image;