Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active July 10, 2017 15:17
Show Gist options
  • Save eric1234/498298 to your computer and use it in GitHub Desktop.
Save eric1234/498298 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;
});
@eric1234
Copy link
Author

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