Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Deferred image loading
var ImageDefer = Class.create({
initialize: function(placeholder) {
this.placeholder = $(placeholder);
this.placeholder.update('Loading image...');
if(ImageDefer.page_loaded) {
this.preload();
} else {
Event.observe(window, 'load', (function() {this.preload()}).bind(this));
}
},
preload: function() {
this.image = new Image();
$(this.image).observe('load', this.loaded.bind(this));
this.image.setAttribute('src', this.placeholder.getAttribute('data-src'));
},
loaded: function() {
this.placeholder.update(this.image);
}
});
ImageDefer.page_loaded = false;
Event.observe(document, 'dom:loaded', function() {
$$('.image-defer').each(function(placeholder) {
new ImageDefer(placeholder);
})
});
Event.observe(window, 'load', function() {
ImageDefer.page_loaded = true;
});
@eric1234

This comment has been minimized.

Copy link
Owner Author

eric1234 commented Jul 29, 2010

Will delay loading an image until the page is fully loaded with everything else. Use like this:

 <span class="image-defer" data-src="my-img.png"></span>

After the page has fully loaded will load the image specified by data-src and insert that image inside the span tag. Useful for cases where the image will not be displayed until later (i.e. when the user does some action that will reveal the image).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.