Skip to content

Instantly share code, notes, and snippets.

@AndreKelling
Created March 15, 2019 11:27
Show Gist options
  • Save AndreKelling/0ccfb7487b546e4fe7f61af65af32d89 to your computer and use it in GitHub Desktop.
Save AndreKelling/0ccfb7487b546e4fe7f61af65af32d89 to your computer and use it in GitHub Desktop.
random image | lazyload with srcset | currently jpg only
// initialise example
import randomImage from './module/randomImage';
randomImage();
<img class="js-randomImage" data-sources='["image1", "image2"]' alt="Thats a random image" />
/*
* currently jpg only!!
* srcset breakpoints are project exclusive
* @todo add option for other image sources
*/
module.exports = () => {
const selector = '.js-randomImage';
const imagePath = '/img/';
const imagePlaceholders = document.querySelectorAll(selector);
Array.prototype.forEach.call(imagePlaceholders, (el) => {
const image = el;
const sourcesArr = JSON.parse(image.dataset.sources);
const randIndex = Math.floor(Math.random() * sourcesArr.length);
const fileName = `${imagePath}${sourcesArr[randIndex]}`;
image.srcset = `${fileName}-m.jpg 250w, ${fileName}-l.jpg 600w, ${fileName}-xl.jpg 968w, ${fileName}-xxl.jpg 1480w, ${fileName}-xxxl.jpg 2200w`;
image.src = `${fileName}-xxxl.jpg`;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment