Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for background images in CSS to be fully loaded [duplicate]

I have a web app that uses external background images loaded in external CSS. Right now, it is possible to use the app before the images have fully rendered, creating weird visual effects.

How can I halt script execution until the images are fully loaded?

It can use normal JavaScript or jQuery. Because the images are loaded in external CSS the normal triggers I have read about don't work.

like image 992
user3306770 Avatar asked Apr 01 '14 14:04

user3306770


People also ask

Can you Lazyload background images?

While <img> tags are the most common way of using images on web pages, images can also be invoked via the CSS background-image property (and other properties). Browser-level lazy-loading does not apply to CSS background images, so you need to consider other methods if you have background images to lazy-load.

How do you get a full background image in CSS?

We can do this purely through CSS thanks to the background-size property now in CSS3. We'll use the html element (better than body as it's always at least the height of the browser window). We set a fixed and centered background on it, then adjust it's size using background-size set to the cover keyword.


2 Answers

If you have an element with a background image, like this

<div id="test" style="background-image: url(link/to/image.png)"><div>

You can wait for the background to load by getting the image URL and using it for an image object in javascript with an onload handler

var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

var img = new Image();
img.onload = function() {
    alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();
like image 97
adeneo Avatar answered Oct 22 '22 23:10

adeneo


There are no DOM events associated with CSS backgrounds. You'd have to count the images, assign onload events and add them as new Image() via JS, increment a counter as they load.

like image 44
Diodeus - James MacFarlane Avatar answered Oct 22 '22 23:10

Diodeus - James MacFarlane