[Pro] LazyLoad JQuery

I found another way to do this, which doesn’t rely on you telling it what event to observe at all. Same method as before, apply Protaculous to the page, use prototype-packed as the library, and paste this into the first Function Body dialog:

var in_viewport = function(elm){
	var offsets = elm.viewportOffset();
	var port = {left:document.viewport.getScrollOffsets()[0],right:document.viewport.getWidth(),top:document.viewport.getScrollOffsets()[1],bottom:document.viewport.getScrollOffsets()[1] + document.viewport.getHeight()};
	var box = {left:offsets[0],right:offsets[0] + elm.getWidth(),top:offsets[1],bottom:offsets[1] + elm.getHeight()};
	if(box.right > port.left && box.left < port.right && box.bottom > port.top && box.top < port.bottom) return true;
	if(box.left < port.right && box.right > port.left && box.bottom > port.top && box.top < port.bottom) return true;
	return false;
}
Element.addMethods({
	lazyload: function(element, options){
		var element = $(element);
		var options = Object.extend({
			placeholder : 'Resources/_clear.gif',
			frequency : 0.2
			}, options || {}
		);
		var remove_placeholder = function (){
			// this function restores the original image source; called when within the viewport
			if ( true === element.hasAttribute('_src') ){
				var old_source = $(element).readAttribute('_src');
				element.writeAttribute({ src: old_source });
				element.writeAttribute({ _src: null });
			}
		}
		var old_source = $(element).readAttribute('src');
		var new_source = options.placeholder;
		element.writeAttribute({ src : new_source }).writeAttribute({ '_src' : old_source });
		var pe = new PeriodicalExecuter(function(){
			if(in_viewport(element)){
				remove_placeholder();
				pe.stop();
			}
		}, options.frequency);
	}
});

$$('img').invoke('lazyload',{placeholder:'Resources/ajaxloader2.gif'});

Remember to change the name of the “loading” image to the one you have placed on your pasteboard somewhere, or just leave the entire options block out to use the Freeway _clear.gif instead.

What this method does is “hook” all images on the page. If they’re off-screen (for any reason – so this works with Carousel, too), they get replaced with the loading image. If any edge or corner of an image is on-screen by as much as one pixel, it will be swapped with its “real” image. Every two tenths of a second, each image checks itself again to be sure. Once an image has been replaced, it calls off this checking process. Once all images have loaded, no further activity is taken on the page.

Walter


actionsdev mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options