Skip to content

Instantly share code, notes, and snippets.

@luzzardi
Last active November 26, 2015 21:53
Show Gist options
  • Save luzzardi/31df52472f1fa463b564 to your computer and use it in GitHub Desktop.
Save luzzardi/31df52472f1fa463b564 to your computer and use it in GitHub Desktop.
LazyLoad.js
<!DOCTYPE html>
<html>
<head>
<title>Lazy Load</title>
</head>
<body>
<!-- sample image -->
<img src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="http://darksouls3.wiki.fextralife.com/file/view/Dark_Souls_3_E3_screenshot_10.jpg">
<img src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="http://images.alphacoders.com/278/278051.jpg">
<img src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="https://wallpaperscraft.com/image/might_and_magic_heroes_6_dragons_battle_wings_21181_3840x2160.jpg">
<hr />
<img id="image-0" width="500" src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="http://darksouls3.wiki.fextralife.com/file/view/Dark_Souls_3_E3_screenshot_10.jpg">
<img id="image-1" width="500" src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="http://images.alphacoders.com/278/278051.jpg">
<img id="image-2" width="500" src="http://wiki.softwarelivre.org/pub/System/DocumentGraphics/blank.gif" data-src="https://wallpaperscraft.com/image/might_and_magic_heroes_6_dragons_battle_wings_21181_3840x2160.jpg">
<script src="LazyLoad.js"></script>
<script>
window.onload = function() {
//var lLoad = new LazyLoad();
var lLoad2 = new LazyLoad([
'image-0',
'image-1',
'image-2'
]);
}
</script>
</body>
</html>
// I didn't test this yet, please feel free to comment
var LazyLoad = function(imagesIds) {
this.imagesSrc = [];
this.init(imagesIds);
return this;
};
LazyLoad.prototype = {
init: function(imagesId) {
if (imagesId && imagesId.length > 0) {
this.getImages(imagesId);
} else {
this.getAllImages();
}
this.load();
},
getImages: function(imagesId) {
for (var index in imagesId) {
var image = document.getElementById(imagesId[index]);
if (typeof image.getAttribute !== 'function') {
continue;
}
this.imagesSrc.push({
'element': image,
'src': image.getAttribute('data-src')
});
}
},
getAllImages: function() {
var images = document.getElementsByTagName('img');
for (var index in images) {
if (typeof images[index].getAttribute !== 'function') {
continue;
}
this.imagesSrc.push({
'element': images[index],
'src': images[index].getAttribute('data-src')
});
}
},
load: function() {
var _this = this;
var image = this.imagesSrc.shift();
if (!image) {
return;
}
var img = new Image();
img.onload = function() {
image.element.src = image.src;
_this.load();
}
img.src = image.src;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment