Created
December 21, 2021 22:15
-
-
Save neruthes/b1785a68e8dbe20e2dd69553f30de1fe to your computer and use it in GitHub Desktop.
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
// ImgMultiSrcLoader.js | |
// Usage: | |
// <img src="1.png" data-multi-src="1.png 2.png https://example.com/3.png"> | |
window.addEventListener('load', function () { | |
document.querySelectorAll('img[data-multi-src]').forEach(function (img) { | |
const srcArr = img.getAttribute('data-multi-src').split(' '); | |
srcArr.forEach(function (src) { | |
const xhr = new XMLHttpRequest(); | |
xhr.addEventListener('load', function (e) { | |
if ((e.target.status === 200 || e.target.status === 304) && img.getAttribute('data-multi-src-loaded') !== 'true') { | |
img.setAttribute('src', src); | |
img.setAttribute('data-multi-src-loaded', 'true') | |
}; | |
}); | |
xhr.open('GET', src); | |
xhr.send(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment