Safari showing white flash upon setting background-image src using Intersection Observer?

I've done extensive research but I'm still struggling to solve this issue. It only seems to be happening on Safari (Mac & iOS), while everything works smoothly on Chrome, Firefox, Edge, and other browsers.

UPDATE: The flickering problem also persists in FireFox...

The problem arises when I try to lazy load images using the IntersectionObserver API and the necessary polyfill. This method swaps out a low-resolution image set as the div's background-image with a high-resolution image stored in a data attribute as soon as it comes into view.

Although the functionality technically 'works' as intended – displaying the low-quality image before switching to the high-quality one – there is an annoying white flicker or flash that occurs during the transition. Could it be the page's white background showing through?

After reading some resources, including this post on Stack Overflow (How to prevent a background image flickering on change), I managed to resolve the jumping issue by preloading the images using the new Image() constructor.

const setBackgroundImage = (e) => { 
  let image = new Image();
  image.onload = () => e.style.backgroundImage = `url(${e.dataset.bgImage})`;
  image.src = e.dataset.bgImage;
};

Here's an example HTML element (PHP):

<div class="my-div" 
     style="background-image: url('<?= $imagePreload ?? $image; ?>');" 
     data-bg-image="<?= $image; ?>"
</div>

I've tried tweaking the backface-visibility: hidden property with no success. I'm not incorporating any animations; simply replacing the src on the div with the preloaded, full-sized image.

Answer №1

To tackle this issue, consider preloading the higher resolution image prior to it becoming visible as the page scrolls. By setting the rootMargin parameter to a value such as 200px while initializing the IntersectionObserver, you can prompt the browser to begin loading the image 200px before it appears within the viewport.

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

Tips for updating the URL and refreshing the page in Safari and Firefox

I am facing an issue with my ajax call that is written in jQuery. It sends a string to the server and receives back some json data. $.ajax({ url: ..., dataType: 'json', success: function(data) { for (var d in ...

Jsoup encounters a complication due to lack of support for Javascript

1http://www.biletix.com/search/TURKIYE/en#!city_sb:İstanbul,date_sb:today Trying to access an element from the provided link results in a message about Javascript not being found. It suggests enabling Javascript and then abruptly closes. As I plan to mi ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Chrome and Internet Explorer are not prompting to save passwords after the input type has been altered by a script

I've encountered an issue with a form that includes: <input type="password" id="password" /> I want to display some readable text temporarily, so I used the following code: $('#password').prop('type', 'text'); ...

Creating a mouse-resistant div with a magnet-like effect

Looking for a way to make a circle move like a magnet effect when the mouse is near, causing elements underneath it to be exposed. If you want to see an example, check out this fiddle link: http://jsfiddle.net/Cfsamet/5xFVc/1/ Here's some initial c ...

Locate all instances of words that begin with a certain character and are immediately followed by numbers within

I am searching for words that start with "mc" and are followed by digits only. let myString = "hi mc1001 hello mc1002 mc1003 mc1004 mc mca"; Expected output = [mc1001, mc1002, mc1003, mc1004] This is how I tackled it: const myRegEx = /(?:^|\s)mc(. ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

Greetings Universe in angular.js

Having trouble creating a Hello World page in angular.js. When I try to display {{helloMessage}}, it shows up instead of Hello World. I'm not sure where the issue lies. Within the folder are two files: angular.min.js and HelloWorld.html. In HelloWorl ...

filter supabase to only show items with numbers greater than or equal to a

Hey there! Currently, I am in the process of setting up a store using nextjs pages router and supabase. However, I have encountered a peculiar bug with my product filtering system when dealing with numbers exceeding 4 digits (e.g., 11000). The structure o ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Unable to append item to JavaScript Map

Currently, I am attempting to insert an item into a Map (similar to a dictionary) using JavaScript within a React Native environment. import React, { Component } from 'react'; import { AppRegistry, View, Button, } from 'react-native& ...

Utilize information from a JSON Array to populate a JavaScript Array

Is there a way to link the data from the $data variable in ajax.php to the this.products[] array in store.js? Both files are separate, so how can I achieve this? The webpage displays the database data returned by ajax.php as shown below: [{"0":"100001"," ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant. var obj = { orders: [ null, { date: "2018-07-09 10:07:18", orderVerified : true, item: [ { name ...

Issues with the onChange function in a Material UI TextField component (React)

I'm currently working on a form using Material UI in React to send data to MongoDB. My form includes DatePickers, Select, and TextField components, all from Material UI. Here's the code snippet for handling state changes: const [project, setProje ...

What is the Best Way to Create a Smooth Border-Bottom Transition?

I'm currently diving into the world of HTML5 and CSS. I want to replicate the layout from . Specifically, I am interested in adding a transition effect to the border bottom of certain elements such as "View Our Listings", "The Agency Daily", "Meet our ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...