Reputation: 371
I am using a below logic to load a background image with fall back default image in case the first image is not available. This image is a dynamic image and it changes page to page and sometimes it may not be there. Hence the default will display. That is fine and the logic is working as expected.
However, for the 1st time page load the browser shows the default image for few second and then it loads the actual image due to that it's flickering.
Could someone tell me how to avoid flickering and load the actual image first and then the default image in case the 1st image not available
$(document).ready(function(){
var imageUrl = 'https://res.cloudinary.com/ct-hero.jpg';
var defaultImageUrl = './images/profile-hero-default.jpg';
$(".hero-bg-video").css("background-image", 'url(' + imageUrl + '), url('+defaultImageUrl+')');
})
Upvotes: 1
Views: 1807
Reputation: 3496
You can use fadeIn
in JS. Please check below code.
$(document).ready(function(){
var imageUrl = 'https://res.cloudinary.com/openproperty/image/upload/q_auto/fox-hill-enfield-ct-hero.jpg';
var defaultImageUrl ='https://www.fragrantnature.com/images/noimage.jpg';
$.when($(".hero-bg-video").css("background-image", 'url(' + imageUrl + '), url('+defaultImageUrl+')')).done($(".hero-bg-video").fadeIn(4000));
});
.hero-bg-overlay {
background-color: rgba(0, 0, 0, 0.4);
z-index: 1;
width: 100%;
height:400px;
}
.hero-bg-video {
width: 100%;
height: 400px;
/*background-image: url(https://res.cloudinary.com/openproperty/image/upload/q_auto/briar-knoll-vernon-ct-hero.jpg), url(https://www.fragrantnature.com/images/noimage.jpg);*/
background-size: 100% 100%;
transition: all 0.5s;
display:none;
}
By default hide the div. After setting background image you can fadeIn the div for smooth animation.
Here is a fiddle
Upvotes: 1