Created
January 11, 2016 13:18
-
-
Save Loac-fr/8e4d862e8b96ff1c895c to your computer and use it in GitHub Desktop.
Lazy load function - adapted from blazy
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
function loadImages(container){ | |
var $ctn = container, | |
els = $ctn.find('.tile-background'), | |
options = {}; | |
options.src = 'data-src'; | |
options.errorClass = 'lazyload--error'; | |
options.successClass = 'lazyload--success'; | |
els.each(function(index){ | |
// adapted from https://github.com/dinbror/blazy/blob/master/blazy.js -- line 171 -- | |
var ele = $(this)[0]; | |
var $that = $(this); | |
var dataSrc = ele.getAttribute(options.src); // fallback to default 'data-src' | |
if (dataSrc) { | |
// var dataSrcSplitted = dataSrc.split(options.separator); | |
// var src = dataSrcSplitted[isRetina && dataSrcSplitted.length > 1 ? 1 : 0]; | |
var src = dataSrc; | |
var isImage = ele.nodeName.toLowerCase() === 'img'; | |
// // cleanup markup, remove data source attributes | |
ele.removeAttribute(options.src); | |
if (isImage || ele.src === undefined) { | |
var img = new Image(); | |
img.onerror = function() { | |
// console.log("image event : error"); | |
if (options.error) options.error(ele, "invalid"); | |
$(this).addClass(options.errorClass); | |
}; | |
img.onload = function() { | |
// console.log("image event : onload"); | |
// Is element an image or should we add the src as a background image? | |
isImage ? ele.src = src : ele.style.backgroundImage = 'url("' + src + '")'; | |
$that.addClass(options.successClass); | |
//could remove | |
if (options.success) options.success(ele); | |
}; | |
img.src = src; //preload | |
} else { | |
ele.src = src; | |
$that.addClass(options.successClass); | |
} | |
} else { | |
//if (options.error) options.error(ele, "missing"); | |
//if (!$(this).hasClass(options.errorClass)) $(this).addClass(options.errorClass); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment