Last active
August 17, 2016 18:42
-
-
Save maxrolon/3336408feffa350891af54de5c0cd384 to your computer and use it in GitHub Desktop.
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
/* | |
* A jQuery dependant module that lazy-loads image urls | |
* Add image urls to a data-src attribute | |
* If node is not of type 'img' then it's load the src | |
* as a background-image | |
* | |
* The functionality can be overridden on a per-node | |
* basis by adding the class 'js-kill-load' to the node | |
* | |
* Instantiate the module via jQuery plugin syntax | |
* e.g. $('img,div').lazyLoad(); | |
*/ | |
var lazyload = function(el){ | |
var iterate = function(){ | |
if ( $(this).hasClass('js-kill-load') ) | |
return; | |
var src = $(this).attr('data-src') || '' | |
, img = new Image() | |
, el = this; | |
img.onload = function(){ | |
if (el.tagName == 'DIV' || el.tagName == 'A' || el.tagName == 'FIGURE' || el.tagName == 'LI' || el.tagName == 'SECTION' ){ | |
el.style.backgroundImage = 'url('+src+')'; | |
} else if (el.tagName == 'IMG'){ | |
if (!! el.parent){ | |
el.parent.replaceChild(img,el); | |
} else { | |
el.src = src; | |
} | |
} | |
$(el).addClass('visible'); | |
} | |
img.src = ''+src; | |
} | |
if (!el){ | |
$('[data-src]').each(iterate); | |
} else { | |
iterate.call(el); | |
} | |
} | |
$.fn.lazyLoad = function(args){ | |
var _ = this; | |
_.each(function(){ | |
new lazyload(this,args); | |
}); | |
} | |
module.exports = lazyload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment