Last active
September 21, 2015 19:52
-
-
Save mszynka/ca83f65a40e467e520a7 to your computer and use it in GitHub Desktop.
Image lazy loader
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
<html> | |
<head> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<img class="lazy"><noscript><img src="images/test1.png"></noscript> | |
<script src="script.js"></script> | |
</body> | |
</html> |
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 _createClass = (function () { | |
function defineProperties(target, props) { | |
for (var i = 0; i < props.length; i++) { | |
var descriptor = props[i]; | |
descriptor.enumerable = descriptor.enumerable || false; | |
descriptor.configurable = true; | |
if ('value' in descriptor) descriptor.writable = true; | |
Object.defineProperty(target, descriptor.key, descriptor); | |
} | |
} | |
return function (Constructor, protoProps, staticProps) { | |
if (protoProps) defineProperties(Constructor.prototype, protoProps); | |
if (staticProps) defineProperties(Constructor, staticProps); | |
return Constructor; | |
}; | |
}) (); | |
function _classCallCheck(instance, Constructor) { | |
if (!(instance instanceof Constructor)) { | |
throw new TypeError('Cannot call a class as a function'); | |
} | |
} | |
var LazyImage = (function () { | |
function LazyImage(DOMImage) { | |
_classCallCheck(this, LazyImage); | |
this._image = new Image(); | |
this._domImage = DOMImage; | |
var div = document.createElement('div'); | |
div.innerHTML = this._domImage.nextSibling.innerHTML; | |
this._imageSrc = div.getElementsByTagName('img') [0].src; | |
div.remove(); | |
} | |
_createClass(LazyImage, [ | |
{ | |
key: 'load', | |
value: function load() { | |
var self = this; | |
this._image.addEventListener('load', function (element) { | |
self._domImage.src = this.src; | |
}); | |
this._image.src = this._imageSrc; | |
} | |
} | |
]); | |
return LazyImage; | |
}) (); | |
function lazyLoadImages(cssClass) { | |
var images = document.getElementsByClassName(cssClass); | |
for (var i = 0; i < images.length; i++) { | |
var limg = new LazyImage(images[i]); | |
limg.load(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment