Tips for verifying the loading status of a background image that is specified as a URL in a CSS file

I have been researching various methods to determine if a background image has finished loading, but most of them are intended for images set in the HTML code.

In my case, I'm using a background URL in a CSS file:

.container{
    background-image: url(/images/rickandmorty.jpg) !important;
    background-repeat: no-repeat;
    background-size: cover;
}

Currently, the text is displaying before the image loads. Is there a way to address this using JavaScript?

Thank you

Answer №1

There is a possibility that adding an onload event to the HTML object might work:

<div class="box" onLoad="runFunction">...</div>

Answer №2

Although this may deviate from the original question, I highly recommend using actual images instead of background-images. This approach offers more flexibility in implementation (such as animations), enables optimization for different resolutions and devices (using srcset), enhances accessibility through alt tags, and makes event listening easier.

To achieve a similar effect to background images, you can simply wrap the image in a container and apply some CSS (like object-fit: cover).

Below is a brief example demonstrating how to use onload event to trigger an animation:

function onImageLoaded() {
  document.querySelector('header').classList.add('loaded')
}

function onImageError() {
  alert('I\'m starting to work up some anxiety about this whole thing!')
}
* {
  box-sizing: border-box;
  position: relative;
}

header {
  aspect-ratio: 21/9;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  color: white;
  text-shadow: 0 0 .25em rgba(0, 0, 0, 0.4);
  background: #869F63;
  z-index: 0;
  overflow: hidden;
}

picture {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  z-index: -1;
  overflow: hidden;
}

picture img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

h1 {
  will-change: transform;
  transition: transform 2000ms;
  transform: translateY(50vh);
  opacity: 0;
}

img {
  will-change: transform;
  transition: transform 2000ms;
  transform: scale(2);
  opacity: 0;
}

.loaded h1,
.loaded img {
  transform: none;
  opacity: 1
}
<header>
  <picture>
    <img src="https://assets.codepen.io/68939/rickandmorty.png" width="680" height="380" alt="Rick & Morty...." onload="onImageLoaded()" onerror="onImageError()" />
  </picture>
  <h1>Rick & Morty</h1>
</header>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using .htaccess for a 301 Redirect

I am currently working on setting up 301 redirects, and regardless of whether I implement the redirect in .htaccess or use a meta or javascript redirect, they all seem to be working. However, there is an issue where the old URL or directory is being append ...

Which JavaScript library or template engine would be most suitable for this scenario?

I am tasked with creating an invite your Facebook friends module that will display the names and photos of your friends, allowing you to message them. It is essential that this feature seamlessly integrates into my website's design, so I need to style ...

Running Angular without dependencies causes it to malfunction

I recently ventured into the world of AngularJS and started by creating a module without any services or factories. Everything was running smoothly until I decided to introduce services and factories into my code. Suddenly, things stopped working. Here is ...

Show the background color on each list element that is being created from the ng-repeat directive

This code dynamically displays a list of li's with images and text. <ul class="presale"> <li ng-repeat="(k,v) in value | groupBy : 'presales_name'" ng-click="showData(k.split(' ').join('-').r ...

Automatically resizing button on media query adjust

I'm experiencing an issue with these 5 buttons in mobile view. On desktop, all 5 buttons are displayed inline. However, on mobile, the last 2 buttons should appear below the first 3. I need them to remain fixed and occupy all available space even when ...

Controlling the behavior of React components in response to updates

I'm currently learning ReactJs and utilizing the ExtReact framework for my project. I have successfully implemented a grid with pagination, which is functioning well. I customized the spinner that appears during data loading and it works as expected ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

Utilize a TypeScript interface in jsDoc comments

By utilizing VSCode, it is nearly achievable to leverage the advantages of Typescript in plain .js files through jsDoc notation and a tsconfig.json configuration: { "compileOnSave": false, "compilerOptions": { "noEmit": true, "allowJs": true, ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

What is the best way to transfer values dynamically with C# code in jQuery?

Can anyone guide me on passing values dynamically in C# code using jQuery? I am currently working on a timepicker control application using jQuery in Visual Studio.NET. I have successfully passed values statically, but I'm unsure how to do it dynamic ...

Troubleshooting CSS media queries: why isn't the display: none property functioning as

I am facing an issue with my code: HTML <section id="offer"> <div class="container"> <div class="row"> <div class="col col-md-12"> <h2>Offer</h2> ...

What is the reason behind only being able to toggle half of the element's classes?

My current project involves using jQuery's .toggleClass() function to implement a favorite button within multiple <div> elements, each containing an <a> element and an <i> element. I am toggling between two Font Awesome icons by swit ...

What is the reason for the directional light shining on the box from behind?

I have inserted a DirectionalLightHelper into my code to provide lighting for a box. The light source is positioned at coordinates (2,2,1), and there are two boxes located at (0,0,0) and (3,3,3) respectively. Surprisingly, the box at (3,3,3) is also being ...

Authenticate with Google using the Javascript API without causing a pop-up to appear

Here is the code I'm using to allow users to log in with their Google account via the Javascript API. HTML <a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a> Javascript function gPOnLoad ...

Is there a specific explanation as to why ng-repeat-start is not functioning properly even with the most recent version of AngularJS?

Can someone please explain why ng-repeat-start is not functioning properly despite using the most up-to-date AngularJS version? I have included it from the CDN: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scr ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

Problems arising from jQuery Mobile, NPM, and WebPack

After spending a considerable amount of time researching and experimenting, I am confident that I could piece something together to make it work. However, I would rather gain an understanding of the root cause of my issue. It is widely acknowledged that j ...