imageLoad.js 1.69 KB
/**
 * Created by moli on 15/7/4.
 */
$.fn.imageLoad = function(beginDis){
    // Lazy image array[object]
    var	lazyArray = $(this);
    var images = [];
    var murl = null;
    // Get page top method
    function pageTop() {
        return ( document.body.clientHeight < document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight ) + Math.max( document.documentElement.scrollTop, document.body.scrollTop );
    }

    // Image load method
    function imgLoad() {
        // Each the images
        lazyArray.each(function() {
            var oft = $( this ).offset();

            if( !oft || this.nodeType === undefined ) return;

            if( oft.top <= pageTop() + ( beginDis || 0 ) ) {
                var original = $( this ).attr( 'original' ) || $( this ).attr( 'data-original' ),
                    _src = $( this ).attr( 'src' );

                // To display the image
                if( original  && !$( this ).hasClass( 'load-img' ) ) {
                    murl = $(this).attr( 'src' );
                    $(this).attr( 'src', original ).removeAttr( 'original').removeAttr( 'data-original');
                    $(this).attr("isOriginal", true);

                    $(this).bind("error", function(){

                        //if($(this).attr("isOriginal") == "true"){
                        $(this).attr( 'src', _src ).removeAttr( 'original' ).removeAttr( 'data-original').addClass( 'load-img' );
                        //  };
                    });

                }
            }

        });
    }

    // Default Check
    imgLoad();

    // Bind the scroll event for window
    $( window ).bind( 'scroll', function() {
        imgLoad();
    });
};