Preload background image

前端 未结 5 545
逝去的感伤
逝去的感伤 2020-12-31 16:40

There\'s tons of articles of how to preload an image, however I can\'t seem to find anything useful about preloading a background image with jquery.

I made a simple

相关标签:
5条回答
  • 2020-12-31 17:04

    You can't as long as it's a background image. Load it normally and then set the background image. Something like this:

    var $img = $( '<img src="' + src + '">' );
    $img.bind( 'load', function(){
        $( '.yourDiv' ).css( 'background-image', 'url(' + src + ')' );
    } );
    if( $img[0].width ){ $img.trigger( 'load' ); }
    

    the last line is needed in some browser in case the image is cached.

    0 讨论(0)
  • 2020-12-31 17:06

    You logic is almost good, but you can not catch events for CSS in jquery.

    You need to load the background image to some <img> element. Catch the event load of that element and when it's fired you change the background image to that src and do the rest of your logic.

    0 讨论(0)
  • 2020-12-31 17:06

    A working example with a mock setTimeout to simulate loading time.

    The relevant jQuery code is:

    $('#LOADING-SIGN-DIV').fadeOut();
    $('#DIV-THAT-NEEDS-PRELOADING').fadeIn();
    
    0 讨论(0)
  • 2020-12-31 17:09

    To do the preloading, why not grab the URL from the css attribute with jQuery? Something like this:

    var bg_url = jQuery("#DIV-THAT-NEEDS-PRELOADING").css('background-image');
    
    // using regex to replace the " url( ... ) "...
    // apologies for my noobish regex skills...
    bg_url = str.replace(/ /g, '', bg_url); // whitespace...
    bg_url = str.replace(/url\(["']?/g, '', bg_url); // next, the 'url("'...
    bg_url = str.replace(/["']?\)/g, '', bg_url); // finally, the trailing '")'...
    
    // without regex, using substring if confident about no quotes / whitespace...
    bg_url = bg_url.substring(4, bg_url.length-1);
    
    // preloading...
    var img = new Image();
    img.onload = function()
    {
        // do transitions here...
    };
    img.src = bg_url;
    
    0 讨论(0)
  • 2020-12-31 17:09

    Here's a post from last week that covered preloading images with jQuery: HTML 5 File load image as background-image

    And here is the solution that post referenced: http://sveinbjorn.org/dataurls_css

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