Created
June 15, 2023 15:21
-
-
Save Maoyeedy/17834de7d257dfa14f07af506a185712 to your computer and use it in GitHub Desktop.
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
function extendImagesWithPicture () { | |
let imgElements = document.querySelectorAll("img") | |
imgElements.forEach(function (img) { | |
let dataSrc = img.getAttribute("data-src") | |
let path = dataSrc.substring(0, dataSrc.lastIndexOf("/") + 1) | |
let imageName = dataSrc.substring(dataSrc.lastIndexOf("/") + 1, dataSrc.lastIndexOf(".")) | |
let picture = document.createElement("picture") | |
let sourceAVIF = document.createElement("source") | |
sourceAVIF.setAttribute("srcset", path + imageName + ".avif") | |
sourceAVIF.setAttribute("type", "image/avif") | |
let sourceWebP = document.createElement("source") | |
sourceWebP.setAttribute("srcset", path + imageName + ".webp") | |
sourceWebP.setAttribute("type", "image/webp") | |
let newImg = document.createElement("img") | |
newImg.setAttribute("src", dataSrc) | |
picture.appendChild(sourceAVIF) | |
picture.appendChild(sourceWebP) | |
picture.appendChild(newImg) | |
img.parentNode.replaceChild(picture, img) | |
}) | |
} | |
extendImagesWithPicture() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment