Created
March 15, 2019 11:27
-
-
Save AndreKelling/0ccfb7487b546e4fe7f61af65af32d89 to your computer and use it in GitHub Desktop.
random image | lazyload with srcset | currently jpg only
This file contains hidden or 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
// initialise example | |
import randomImage from './module/randomImage'; | |
randomImage(); |
This file contains hidden or 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
<img class="js-randomImage" data-sources='["image1", "image2"]' alt="Thats a random image" /> |
This file contains hidden or 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
/* | |
* 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