CSS and JavaScript implementation for Smooth Lazy Loading of Background Images with No Flickering

I've been experimenting with lazy loading background images, starting with a low resolution image that is then replaced with a high resolution one. I've tested various lazy loaders, but they all seem to exhibit the same issue - a flicker when the image switches. I tried using Yall Lazy Image Loader and made some tweaks so that the image is loaded before being applied to the background, but there's still a brief white flicker as the image changes. This flicker is more noticeable in Firefox, especially when the image isn't cached.

Any suggestions? Here's the codepen link:

https://codepen.io/kehza/pen/PoPKZBa

newImg.onload = function () {
    this.backgroundTarget.classList.remove(lazyBackgroundClass);
    this.parentNode.removeChild(this);
};

Appreciate any help!

Answer №1

If you render both elements to the DOM initially and then adjust the opacity values later, it could potentially offer better performance as the browser won't have to repaint or composite the layers again. An efficient approach is to utilize the new "loading=lazy" attribute which allows the browser to handle the loading process for you. You can modify the code below to make use of background images instead of inline images. Additionally, consider applying the will-change attribute on .wrapper if any flickering issues persist.

<div class="wrapper">
  <img class="lowres" src="https://cdn.shopify.com/s/files/1/0254/2426/5278/files/Suited-Racer_200x.jpg" />
  <img class="highres" loading="lazy" src="https://cdn.shopify.com/s/files/1/0254/2426/5278/files/Suited-Racer_1920x.jpg" />
</div>

Javascript

document.querySelectorAll('img.highres').forEach(img => {
  img.addEventListener('load', e => {
    img.parentElement.classList.add('highres-loaded'))
  })
})

CSS

.wrapper {
  position: relative;
  line-height: 0;

  /* set fixed size for your page */
  width: 100%;
  height: 500px;
}
.wrapper img {
  position: absolute;
  display: inline-block;
  width: 100%;
  height: 100%;
}
.highres {
  opacity: 0;
}
.highres-loaded .lowres {
  opacity: 0;
}
.highres-loaded .highres {
  opacity: 1;
}

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

Finding out the nature of nullable attributes within an object: How can it be done?

I'm facing an issue with saving incomplete forms where I have a form being filled out by a user and I wish to allow the form to be saved even if it's not fully complete. Before sending the object to my API, I need to set any null attributes to e ...

Implement a functionality to retrieve uploaded files by utilizing the onChange event of a

I'm currently working on converting this jQuery code to React: //Js $(".custom-file-input").on("change", function() { var files = Array.from(this.files) var fileName = files.map(f =>{return f.name}).join(", ") $( ...

Achieving the new value without retrieving the old value in a jQuery on('save') event

I am currently utilizing X-editable and attempting to retrieve the value of an element when a user changes it. However, I am encountering difficulties as I am only getting the previous value instead of the changed value. For example, if the original value ...

Issue: "Download unsuccessful - File not found" message received while attempting to download a file from an application hosted on Heroku

I created a basic application using Flask that works perfectly on my local host. The homepage of the app allows users to download PDF files from a link, but when I attempt to do the same on the deployed app on Heroku, it displays an error message saying "F ...

Ways to verify the user's authentication status on the server end

Before displaying an HTML page, I need to verify user authentication. Here is a snippet from my server.js: const express = require('express'); var jquery = require('jquery'); var admin = require("firebase"); const app = expre ...

Tips on harnessing the power of PhantomJS and node.js for web scraping

After successfully installing node-phantom using the command npm install node-phantom, I encountered an error when running this code: Cannot find module 'webpage' var webpage = require('webpage').create(), url = "https://www.exampl ...

Using jQuery to update elements with the same class in HTML

This morning, I stumbled upon a rather perplexing issue. Despite my attempts to find a solution on SO, all I came across were methods involving data loading into HTML or a complete page refresh. My aim is to utilize jQuery's $.ajax function to update ...

Are you able to develop a customized TestNG Listener to cater to your specific requirements?

I have developed a unique concept for a TestNG listener that meets my specific requirements. Essentially, I aim to design a custom listener that generates a report using a predefined HTML format. The crux of my idea revolves around declaring the listener ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

Streaming large files with Node.js can lead to significant memory consumption and potential memory errors like OOM

My current project involves using node.js to download large files (300MB) from a server and then piping the response to a file write stream. While I have a good understanding of how pipes work in Node.js, I am encountering an issue where the memory usage o ...

Ways to extract information from a JavaScript popup window before it closes

I am currently facing the challenge of detecting the existence of a form field in a closed popup window. Unfortunately, I do not have control over the child window, but it is within the same domain as the parent window. I have explored the possibility of ...

Unable to display a Google map within a webview when viewing a local HTML file

I am currently working with a local HTML file called basicmap.html that includes the following code: <!DOCTYPE html> <html> <head> </head> <body> <div id="map"></div> <script> ...

Using onClick from another tag, React can dynamically change the style of a className

I am looking to dynamically change the position of a div with the class name "myMenu" using an onClick event triggered from an h1 tag element. Specifically, my current setup looks like this: <div className="myMenu"> <button onClick={()=> t ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

Use jQuery to move list items up or down when clicking on an element outside the list, as long as they contain checked checkboxes

I am in need of creating a user interface that includes both a "Move Up" button and a "Move Down" button. These buttons will allow users to reposition list items by moving them up or down within the list, based on whether they click the "Move Up" or "Move ...

The output from a spawned process behaves oddly when it is being piped

I have a goal to convert the session of a process execution into JSON (similar to [{ type: 'stdout', data: 'What's your name?' }, { type: 'stdin', data: 'Alex.' }, { type: 'stdout', data: 'Hi, Ale ...

Alternate solution for outdated browsers that stretches to the maximum height available

Is there a way to ensure equal height for all children using flexbox, but also have a fallback option for browsers like IE10 and similar? I tried using display: table and display: table-cell, but it doesn't seem to work well with fixed heights. Addit ...

Issue with border-color in CSS on Chrome tables

Here is a table style I have defined for selected elements: tr[selected] { background: #FFF; border-color: #000000; color: #000000; } To apply this style, I use JavaScript: $this.unbind().change(function () { element = $(this).parent ...

Template for event cell details in Angular2 calendar view

Currently utilizing [angular-calendar] from github.com/mattlewis92/angular-calendar . My goal is to incorporate my own template as a detailed view for events. I am aiming to achieve a similar effect as shown in the image: final effect So far, I ha ...