Proper jQuery image load()?

前端 未结 3 1759
小蘑菇
小蘑菇 2021-01-26 14:17


        
3条回答
  •  误落风尘
    2021-01-26 15:11

    A good way to test whether an image has loaded or not is to try and access its dimensions, if you can get the height or width of an image, you can assume it has loaded and greyscale it. Therefore you could modify your code to do this:

    jQuery('.my-image').each(function()
    {
        var greyscale = function(image)
        {
            jQuery(image).greyScale({
                fadeTime: 200,
                reverse: false
            });
        }
    
        if ( jQuery(this).width() )
        {
            // it's loaded, greyscale its ass
            greyscale( this );
        }
        else
        {
            // wait for the load
            $(this).load(greyscale);
        }
    });
    

    In this situation, since you want the image to be greyscale first I'd recommend inserting images programmatically:

    Where your tags would be, replace them with

    tags where you add a data-src attribute, this will contain the image's URL.

    When you're document has loaded, use a script that goes through all the

    tags and insert the tags within the
    tags, for example:

    jQuery('div.my-image').each(function()
    {
        var el = jQuery( this );
    
        // get the src for the image
        var src = el.data( 'src' );
    
        // start loading the image
        var img = new Image();
    
        img.onload = function()
        {
            // greyscale it
            jQuery(img).greyScale({
                fadeTime: 200,
                reverse: false
            });
    
            // append it
            el.append( img );
        }
    
        // load the image by setting the src
        img.src = src;
    });
    

提交回复
热议问题