-
-
Save e-orlov/f61ac690597cfcbe1cb9 to your computer and use it in GitHub Desktop.
Deferred image loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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