Skip to content

Instantly share code, notes, and snippets.

@RobinDev
Last active November 8, 2018 11:53
Show Gist options
  • Save RobinDev/74844c95da85e8e2babec4dc795a9656 to your computer and use it in GitHub Desktop.
Save RobinDev/74844c95da85e8e2babec4dc795a9656 to your computer and use it in GitHub Desktop.
Image simple lazy Loader with SEO enhancement
/**
* 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;
});
}
@RobinDev
Copy link
Author

RobinDev commented Nov 8, 2018

@RobinDev
Copy link
Author

RobinDev commented Nov 8, 2018

#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