Last active
July 10, 2017 15:17
-
-
Save eric1234/498298 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
Will delay loading an image until the page is fully loaded with everything else. Use like this:
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).