hhhzzzsss
hhhzzzsss

Reputation: 21

Gatsby image onLoad fires in develop mode but not in build

I recently tried out developing a site in Gatsby, and I have an animation that triggers when an image fires its onLoad event. This works fine in gatsby develop, but when I do gatsby build onLoad never fires.

If I manually change the image src in inspect element to make it load a new image, the event fires. I'm guessing that it has to do with server-side rendering, but I don't know how to fix this without forcing everything to render client-side. The image still takes time to load up after all, so why won't onLoad fire in the build? How can I make it fire?

Here's the code with some irrelevant parts cut out.

import React from 'react';
import  * as bannerStyles from './banner.module.css';
import negative_forest from '../images/negative_forest.png';

export default class Banner extends React.Component {
    constructor(props) {
        super(props);
        this.wrapper = React.createRef();
        this.img = React.createRef();
        this.textContainer = React.createRef();
        this.onImgLoad = this.onImgLoad.bind(this);
    }

    render() {
        return <div className={bannerStyles.wrapper} ref={this.wrapper}>
            <img onLoad={this.onImgLoad} src={negative_forest} alt="Negative Forest" className={bannerStyles.img} ref={this.img} />
            <div className={bannerStyles.textContainer} ref={this.textContainer}>
                <h1 className={bannerStyles.text}>Title</h1>
                <h2 className={bannerStyles.text}>Subtitle</h2>
            </div>
        </div>;
    }

    onImgLoad() {
        alert('loaded image');
        this.img.current.style.animation = `${bannerStyles.imgfade} 3s linear 0s 1 normal forwards`;
        this.textContainer.current.style.animation = `${bannerStyles.textfade} 3s linear 0s 1 normal forwards`;
    }
}

edit: I tried loading the site in a different browser, and it fired the event the first time but not subsequent times, so I think it has to do with caching instead. My bad.

Upvotes: 1

Views: 607

Answers (1)

hhhzzzsss
hhhzzzsss

Reputation: 21

I eventually figured it out. It didn't really have much to do with Gatsby. React's onLoad event doesn't fire when the browser caches the image. It worked properly when I added a check for this.img.current.complete in both componentDidMount and componentDidUpdate, similar to this solution: NextJS: Images loaded from cache don't trigger the onLoad event.

Upvotes: 1

Related Questions