How can I check if a background image is loaded?

后端 未结 10 1503
囚心锁ツ
囚心锁ツ 2020-11-22 07:05

I want to set a background image on the body tag, then run some code - like this:

$(\'body\').css(\'background-image\',\'http://picture.de/image.png\').load(         


        
10条回答
  •  青春惊慌失措
    2020-11-22 07:37

    I've located a solution that worked better for me, and which has the advantage of being usable with several images (case not illustrated in this example).

    From @adeneo's answer on this question :

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

    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();
    

提交回复
热议问题