Last active
November 8, 2018 11:53
-
-
Save RobinDev/74844c95da85e8e2babec4dc795a9656 to your computer and use it in GitHub Desktop.
Image simple lazy Loader with SEO enhancement
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
/** | |
* Simple Image Lazy Loader | |
* @author: Robin D. https://www.robin-d.fr/ | |
* idea borrow from : https://davidwalsh.name/lazyload-image-fade | |
* Example : <span data-img="https://source.unsplash.com/collection/993239/600x400">Random Image from Unsplash</span> | |
* will be transform to : <img src="https://source.unsplash.com/collection/993239/600x400" alt="Random Image from Unsplash" /> | |
*/ | |
export function imgLazyLoad() { | |
[].forEach.call(document.querySelectorAll('[data-img]'), function(img) { | |
let newDomImg = document.createElement('img'); | |
let src = img.getAttribute('data-img'); | |
img.removeAttribute('data-img'); | |
for (var i = 0, n = img.attributes.length; i < n; i++){ | |
newDomImg.setAttribute(img.attributes[i].nodeName, img.attributes[i].nodeValue); | |
} | |
if (newDomImg.getAttribute('alt') === null && img.textContent != '') { | |
newDomImg.setAttribute('alt', img.textContent); | |
} | |
newDomImg.setAttribute('src', src); | |
img.outerHTML = newDomImg.outerHTML; | |
}); | |
} |
#SEO tip :
<a href="my-image" data-img="my-image">my image</a>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test with delay (npm) : http://localhost:4567/5000/https://source.unsplash.com/collection/993239/600x400