title: Image onLoad event in isomorphic/universal react - register event after image is loaded
body: <p>In isomorphic rendered page image can be downloaded before main <code>script.js</code> file. So image can be already loaded before <code>react</code> register <code>onLoad</code> event - never trigger this event.</p>
  
  <p><code>script.js</code></p>
  
  <pre><code>constructor(props) {
      super(props);
      this.handleImageLoaded = this.handleImageLoaded.bind(this);
  }
  
  handleImageLoaded() {
      console.log('image loaded');
  } 
  
  render() {
      return (
          &lt;img src='image.jpg' onLoad={this.handleImageLoaded} /&gt;
      );
  }
  </code></pre>
  
  <hr>
  
  <h3>Scenario 1 - <code>image.jpg</code> is bigger than <code>script.js</code></h3>
  
  <p><a href="https://i.stack.imgur.com/cE6Mu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cE6Mu.jpg" alt="image.jpg is bigger than script.js"></a></p>
  
  <p>In this scenario everything is working fine. Event is registered before image is finally loaded so in console is <code>image loaded</code> message.</p>
  
  <hr>
  
  <h3>Scenario 2 - <code>image.jpg</code> is smaller than <code>script.js</code></h3>
  
  <p><a href="https://i.stack.imgur.com/tKbrd.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/tKbrd.jpg" alt="image.jpg is smaller than script.js"></a></p>
  
  <p>This scenario you can see problem described at the beginning of post. <code>onLoad</code> event is not triggered. </p>
  
  <hr>
  
  <h3>Question</h3>
  
  <p>What can I do in order to trigger <code>onLoad</code> event in <strong>scenario 2</strong>?  </p>
  
  <hr>
  
  <h3>EDIT: Soviut answer implementation</h3>
  
  <p>To detect if image is ready on render you should check <code>complete</code> property on pure javascript <code>img</code> object:</p>
  
  <pre><code>constructor(props) {
      super(props);
      this.state = { loaded: false };
      this.handleImageLoaded = this.handleImageLoaded.bind(this);
      this.image = React.createRef();
  }
  
  componentDidMount() {
      const img = this.image.current;
      if (img &amp;&amp; img.complete) {
          this.handleImageLoaded();
      }
  }
  
  handleImageLoaded() {
      if (!this.state.loaded) {
          console.log('image loaded');
          this.setState({ loaded: true });
      }
  } 
  
  render() {
      return (
          &lt;img src='image.jpg' ref={this.image} onLoad={this.handleImageLoaded} /&gt;
      );
  }
  </code></pre>