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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With