Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@e-orlov
Forked from eric1234/image-defer.js
Created February 4, 2016 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e-orlov/f61ac690597cfcbe1cb9 to your computer and use it in GitHub Desktop.
Save e-orlov/f61ac690597cfcbe1cb9 to your computer and use it in GitHub Desktop.
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;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment