티스토리 뷰
이전 글: 웹 최적화 캐시 Etag, Cache-Control
웹 최적화 캐시 Etag, Cache-Control
캐시 전략은 클라이언트와 서버에 각각 적용할 수 있다. 중요한 점은 서버에 I/O Call를 발생시키지 않아야 좋은 것이다. 서버에서 Redis나 Ehcache 활용하거나, 아니면 DB 수준에서 캐싱을 사용하든
koolreview.tistory.com
https://www.npmjs.com/package/sharp
sharp
High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images. Latest version: 0.33.5, last published: 12 days ago. Start using sharp in your project by running `npm i sharp`. There are 4673 other projec
www.npmjs.com
sharp 라이브러리에서 webp으로 변환해주는 간단한 코드가 있다.
설치: npm init -> npm install sharp
더 자세한 코드는 라이브러리 문서를 읽으면 해결할 수 있다.
import shartp from "sharp"
sharp('prevImage.jpg')
.toFormat('webp')
.toFile('webpImage.webp', (err, info) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Success:', info);
}
});
jpg를 webp으로 변환해서 2개의 사진을 가지고 있으면 된다.
그 이후 HTML에서 webp을 img src에 넣어주면 된다.
<img src="./webpImg/testImg.webp" alt="img">
그리고 webp 이미지 조그만한 사진을 하나 따로 준비해두고, 아래 JS에서 처럼 이미지 객체를 만들고 미리 호출해서 로드가 되는지 확인한다. 그리고 동작을 하지 않는다면 replace를 이용해서 url를 변경해주면 된다.
추가적으로 확장자가 모든 이미지가 동일하지 않을 것이다. 그런 경우 img tag에 data로 넣어서 해당 이미지의 확장자를 넣어두고 지원하지 않는 라이브러리에서는 해당 확장자를 data에서 빼서 쓰면 된다.
document.addEventListener("DOMContentLoaded", function () {
supportsWebP(function (supported) {
if (!supported) {
document.querySelectorAll('img').forEach(function (img) {
var webpSrc = img.getAttribute('src');
if (webpSrc && webpSrc.endsWith('.webp')) {
var jpgSrc = webpSrc.replace('.webp', '.jpg');
img.setAttribute('src', jpgSrc);
}
});
}
});
});
function supportsWebP(callback) {
var webP = new Image();
webP.src = "./webpImg/testImg.webp";
webP.onload = webP.onerror = function () {
callback(webP.height === 40);
};
}
'코딩 관련 > 자바스크립트' 카테고리의 다른 글
Vite + Spring Boot 짬뽕 (0) | 2024.10.29 |
---|---|
Zustand, Vanilla js에서 사용하여 데이터에 집중하자 (0) | 2024.07.26 |
Youtube Ifram을 하는데 썸네일, 또는 버튼을 바꾸고 싶은 경우 (0) | 2024.06.28 |
'Vanilla JS X Dom 객체를 이용한 SPA처럼 페이지 만드는 방법' (0) | 2024.06.25 |
Currying/Partial Application 인수를 하나를 받아, 복잡도를 낮추는 방법 (0) | 2023.10.19 |