Skip to content

Instantly share code, notes, and snippets.

@siriokun
Last active December 20, 2015 06:38
Show Gist options
  • Save siriokun/6086957 to your computer and use it in GitHub Desktop.
Save siriokun/6086957 to your computer and use it in GitHub Desktop.
Load images when visible in viewport.
<div data-defer="view"
data-img-src="//path/to/image.jpg"
data-img-alt="imgtitle"
data-img-width="150">
Image text placeholder
</div>
( function( $ ) {
if ( typeof $.proxy == 'undefined' ) {
$.proxy = function( callback, context ) {
var proxy = function() {
callback.apply( context, arguments );
}
return proxy;
};
}
var vController = function() {
this.init();
};
vController.prototype = {
init: function() {
var that = this;
var s = $( '[data-defer="view"]' );
s.each( function() {
var t = $( this ), p = t.parent(), w = Number( t.attr( "data-img-width" ) ), h = Number( t.attr( "data-img-height" ) );
p.css( { width: w, height: h } );
});
this.objs = [];
var w = $( window ), top = w.scrollTop(), bottom = top + w.height(), i;
s.each( function() {
var t = $( this ), p = t.parent(), off = p.offset();
var o = {
a: t,
p: p,
top: off.top,
bottom: off.top + p.innerHeight()
};
if ( o.top < bottom && o.bottom > top ) {
that.load( o );
}
else {
that.objs.push( o );
}
});
$( window ).scroll( $.proxy( this.scroll, this ) );
},
scroll: function() {
var w = $( window ), top = w.scrollTop(), bottom = top + w.height(), i;
for ( i = this.objs.length - 1; i >= 0; i-- ) {
if ( this.objs[i].top < bottom ) {
this.load( this.objs[i] );
}
}
},
load: function( o ) {
var t = o.a;
var c = $( "<img />" );
var f = function() { t.html( c ); };
c.load( f );
c.attr( "src", t.attr( "data-img-src" ) );
c.attr( "alt", t.attr( "data-img-alt" ) );
c.attr( "border", 0 );
}
};
$( function() {
var vC = new vController();
})
}) ( jQuery );
// http://www.oscon.com/oscon2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment