How can I check if a background image is loaded?

后端 未结 10 1359
囚心锁ツ
囚心锁ツ 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:48

    Here is a simple vanilla hack ~

    (function(image){
      image.onload = function(){ 
                       $(body).addClass('loaded-background');
                       alert('Background image done loading');
                       // TODO fancy fade-in
                     };
      image.src    = "http://picture.de/image.png";
    })(new Image());
    
    0 讨论(0)
  • 2020-11-22 07:53

    There are no JS callbacks for CSS assets.

    0 讨论(0)
  • 2020-11-22 07:53

    Something like this:

    var $div = $('div'),
      bg = $div.css('background-image');
      if (bg) {
        var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
          $img = $('<img>').attr('src', src).on('load', function() {
            // do something, maybe:
            $div.fadeIn();
          });
      }
    });
    
    0 讨论(0)
  • 2020-11-22 07:55

    Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:

    Read the article:

    http://catmull.uk/code-lab/background-image-loaded/

    or go straight to the plugin code:

    http://catmull.uk/downloads/bg-loaded/bg-loaded.js

    So just include the plugin and then call it on the element:

    <script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
    <script type="text/javascript">
       $('body').bgLoaded();
    </script>
    

    Obviously download the plugin and store it on your own hosting.

    By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:

    <script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
    <script type="text/javascript">
       $('body').bgLoaded({
          afterLoaded : function() {
             alert('Background image done loading');
          }
       });
    </script>
    

    Here is a codepen demonstrating it working.

    http://codepen.io/catmull/pen/Lfcpb

    0 讨论(0)
提交回复
热议问题