A Pen by Julian Llanten on CodePen.
Created
May 18, 2022 22:00
-
-
Save JulianLlanten8/efe7792a09e5cd8e21addde0f35dafa2 to your computer and use it in GitHub Desktop.
Webp and Vue
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
<div id="app"> | |
<h1>Webp supported: {{ webpSupported ? 'Yes' : 'No' }}</h1> | |
<!-- Show the chair photo --> | |
<img | |
:src="transformImgExt('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1055221/chair_1000.png')" | |
width="150px" | |
/> | |
<!-- Show the dog photo --> | |
<img | |
:src="transformImgExt('https://s3-us-west-2.amazonaws.com/s.cdpn.io/1055221/dog_1000.jpg')" | |
width="150px" | |
/> | |
</div> |
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
let app = new Vue({ | |
// What should we mount our Vue instance to? | |
el: "#app", | |
// App data | |
data: { | |
// We'll initially assume webp is supported | |
webpSupported: true | |
}, | |
// Methods | |
methods: { | |
/** | |
* Helper to transform image extension. | |
* Checks if webp is supported, and will swap out the image extension accordingly. | |
*/ | |
transformImgExt (url) { | |
// If webp is supported, transform the url | |
if (this.webpSupported) { | |
return url.replace(/\.\w{1,5}$/, ".webp"); | |
} else { // Otherwise, just return the original | |
return url; | |
} | |
} | |
}, | |
/** | |
* When app is "created", we'll run some checks to see if the browser supports webp | |
*/ | |
created() { | |
(async () => { | |
// If browser doesn't have createImageBitmap, we can't use webp. | |
if (!self.createImageBitmap) { | |
this.webpSupported = false; | |
return; | |
} | |
// Base64 representation of a white point image | |
const webpData = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoCAAEAAQAcJaQAA3AA/v3AgAA='; | |
// Retrieve the Image in Blob Format | |
const blob = await fetch(webpData).then(r => r.blob()); | |
// If the createImageBitmap method succeeds, return true, otherwise false | |
this.webpSupported = await createImageBitmap(blob).then(() => true, () => false); | |
})(); | |
} // End created | |
}) |
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
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment