DEV Community

alireza valizade
alireza valizade

Posted on • Edited on

9 6

Background-Image-On-Load

Background-Image-On-Load

A simple way to check background-image is loaded.

Installation

npm:

npm install background-image-on-load --save
Enter fullscreen mode Exit fullscreen mode

yarn:

yarn add background-image-on-load
Enter fullscreen mode Exit fullscreen mode

Usage

import React, { Component } from 'react';
import BackgroundImageOnLoad from 'background-image-on-load';

class App extends Component {

  state = {
    bgIsLoaded: false
  };

  render() {
    const { bgIsLoaded } = this.state;
    return (
        <div
          style={{ 
            height: 300,
            backgroundPosition: 'center',
            backgroundSize: 'cover',
            backgroundImage: `url(${!bgIsLoaded ? 'https://picsum.photos/310/310?blur' : 'https://picsum.photos/1600/310'})`
          }}
        >
          <BackgroundImageOnLoad
            src={'https://unsplash.it/1200/310?random'}
            onLoadBg={() =>
              this.setState({
              bgIsLoaded: true
            })}
            onError={err => console.log('error', err)}
          />
        </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

If you like this library please click on the start button on github.

https://github.com/alirezavalizade/background-image-on-load

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (3)

Collapse
 
notrealdev profile image
notrealdev

Hi, do you have valilla js version for this?

Collapse
 
alirezavalizade profile image
alireza valizade

it's only 3 lines. the rest is customizable

const img = new Image(src);
img.onload = () => {
  .....
};
Collapse
 
notrealdev profile image
notrealdev

Not works for me.
backgroundImage does not work completely in my opinion.
I must use dataURL for it, thank you.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs