JS is waiting for CSS background image to load

It is easy to save javascript while waiting for some images to load if these are classic HTML images.

But I can’t figure out how to do the same if the image is loading as CSS backuground-image !

Is it possible?

The jQuery .load() method doesn't seem to apply .. and I miss ideas

+4
source share
4 answers

It searches for elements with the src or backgroundImage css attribute and calls the action function when loading their images.

 /** * Load and wait for loading images. */ function loadImages(images, action){ var loaded_images = 0; var bad_tags = 0; $(images).each(function() { //alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display")); var image = new Image(); var src = $(this).attr("src"); var backgroundImage = $(this).css("backgroundImage"); // Search for css background style if(src == undefined && backgroundImage != "none"){ var pattern = /url\("{0,1}([^"]*)"{0,1}\)/; src = pattern.exec(backgroundImage)[1]; }else{ bad_tags++; } // Load images $(image).load(function() { loaded_images++; if(loaded_images == ($(images).length - bad_tags)) action(); }) .attr("src", src); }); } 
+1
source

One alternative approach would be to extract image data via AJAX as base64-based encoded png , and apply it to the element background-image property.

For instance:

 $.get('/getmyimage', function(data) { // data contains base64 encoded image // for ex: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== $('#yourElement').css('background-image', 'url("' + data + '")'); }); 

You will also need the server side of the script, which reads the image, converts it to png (and can cache it in base64) and returns the same.

+1
source

this is unverified code, but try the following:

 $(document).ready( function() { var imgSrc = $('theTargerElement').css('background-image'); var imgTag = $('<img>').attr('src',imgSrc).appendTo( 'body' ); } ); $(document) .load( function() { // do stuff } ); 
0
source

Try this one ...

Its a jQuery plugin that gives you the ability to wait for images to load

Project home

The @SO thread The official way to ask jQuery to wait for all images to load before doing anything

Reply @SO (ShortLink)

0
source

Source: https://habr.com/ru/post/1393471/


All Articles