Image onLoad event in isomorphic/universal react - register event after image is loaded

后端 未结 5 726

In isomorphic rendered page image can be downloaded before main script.js file. So image can be already loaded before react register onLoad

5条回答
  •  隐瞒了意图╮
    2020-12-23 15:23

    img.complete is true even when the src load fails.

    complete - Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no src value.

    1. Use naturalWidth as determinant whether the img load was successfull or not
        state = {
            isLoading: true,
            hasError: false,
        }
    
        myRef = React.createRef();
    
        componentDidMount() {
            const img = this.myRef.current;
    
            if (img && img.complete) {
                if (img.naturalWidth === 0) {
                    this.handleOnError();
                } else {
                    this.handleImageLoaded();
                }
            }
        }
    
        handleImageLoaded = () => {
            if (this.state.isLoading) {
                this.setState({ isLoading: false });
            }
        }
    
        handleOnError = () => {
            this.setState({ hasError: true });
        }
    
        render() {
            return (
                {alt}
            );
        }
    
    1. Another way is to add "check" image in componentDidMount a set eventHandler to it and let the check image be the one to handle eventListeners
    componentDidMount() {
       const testImg = new Image();
       testImg.onerror = this.handleOnError;
       testImg.onload = this.handleImageLoaded;
       testImg.src = this.props.src; // important to set eventlisteners before src
    }
    
    

提交回复
热议问题