투케이2K

572. (javaScript) 자바스크립트 Cache Storage 캐시 스토리지 사용해 캐시 생성 및 저장 , 캐시 목록 조회 , 특정 캐시 삭제 실시 본문

JavaScript

572. (javaScript) 자바스크립트 Cache Storage 캐시 스토리지 사용해 캐시 생성 및 저장 , 캐시 목록 조회 , 특정 캐시 삭제 실시

투케이2K 2026. 7. 14. 19:19
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++ / Vscode

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript / Cache Storage / 캐시 스토리지


- 사전) 👉 Cache Storage 캐시 스토리지 간략 설명 : 

  >> 캐시 스토리지는 브라우저가 제공하는 웹 리소스 저장소입니다.

  >> 캐시 스토리지를 사용해서 JavaScript 에서 직접 캐시 데이터를 저장하고 조회할 수 있습니다.

    - 브라우저의 Memory/Disk Cache는 개발자가 직접 제어할 수 없습니다.
  
  >> 캐시 스토리지 특징 : 

    - Request-Response 구조
    - 비동기 방식
    - 대용량 저장 가능
    - 파일 저장 가능
    - API 응답 저장 가능

  >> 캐시 스토리지 일반적 저장 구조 : 

    Cache Storage
    ├─ app-cache-v1
    │   ├─ /api/user
    │   ├─ /js/app.js
    │   └─ /css/main.css
    │
    └─ image-cache
        ├─ logo.png
        └─ banner.png

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
    <title>javaScriptTest</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- [반응형 구조 만들기] -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

    <!-- [Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화] -->
    <meta name="google" content="notranslate">

    

    <!-- 내부 CSS 스타일 지정 -->
    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin : 0 auto;
            padding : 0;
            border : none;
            background-color: #666;
        }

    </style>





    <!-- ✅ [스크립트 : CDN 주소 설정] --> 
    <!-- <script src="https://code.jquery.com/jquery-latest.min.js"></script> -->







    <!-- [자바스크립트 코드 지정] -->
    <script type="module">    


    // -----------------------------------------------------------------
    // ✅ [Window.onload 웹 브라우저 로드 완료]
    // -----------------------------------------------------------------
    window.onload = async function() {
        console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");

        try {

            // ------------------------------------------------
            // 🟦 현재 Cache Storage 지원 여부 확인
            // ------------------------------------------------ 
            const isSupportedCacheStorage = function(){
                try {
                    return ('caches' in window) ? true : false;
                }
                catch (exception){
                    console.error('isSupportedCacheStorage : exception : ', exception);
                    return false;
                }
            }


            // ------------------------------------------------
            // 🟦 캐시 생성 및 저장
            // ------------------------------------------------ 
            const cache = await caches.open('app-cache-v1');

            // 👉 [단일 저장 방식]
            await cache.add('https://code.jquery.com/jquery-latest.min.js');

            // 👉 [여러개 저장 방식]
            // file:// 프로토콜에서 Cache API 사용 시 에러 발생 유의
            // Cache Storage API 는 http:// 및 https:// 기반 요청만 지원
            /*
            await cache.addAll([
                '/css/main.css',
                '/js/app.js',
                '/images/logo.png'
            ]);
            // */

            // 👉 [직접 데이터 저장 방식]  
            // file:// 프로토콜에서 Cache API 사용 시 에러 발생 유의     
            // Cache Storage API 는 http:// 및 https:// 기반 요청만 지원      
            /*
            await cache.put(
                '/api/version',                
                new Response(
                    JSON.stringify({
                        version: '1.0.0',
                        env: 'prod'
                    })
                )
            );
            // */


            // ------------------------------------------------
            // 🟦 특정 캐시 저장 여부 확인 및 내용 읽기
            // ------------------------------------------------   

            const response = await caches.match('https://code.jquery.com/jquery-latest.min.js');

            if(response){
                console.log('캐시 존재 : ', response);
                            
                const data = await response.text();

                console.log('data : ', data);

            }
            else {
                console.error('캐시 없음');
            }


            // ------------------------------------------------
            // 🟦 저장된 캐시 이름 조회 및 Cache Storage 전체 정보 출력
            // ------------------------------------------------             
            const cacheNames = await caches.keys();

            console.log('cacheNames : ', cacheNames);
            
            if (cacheNames !== null && cacheNames !== undefined){

                for (const cacheName of cacheNames) {

                    const cache = await caches.open(cacheName);
                    
                    const requests = await cache.keys();

                    console.log('cacheName : ', cacheName, ' / requests : ', requests);

                    if (requests !== null && requests !== undefined){

                        for (const request of requests) {
                           
                            /*
                            body: (…)
                            bodyUsed: false
                            cache: "default"
                            credentials: "omit"
                            destination: ""
                            duplex: "half"
                            headers: Headers {}
                            integrity: ""
                            isHistoryNavigation: false
                            isReloadNavigation: false
                            keepalive: false
                            method: "GET"
                            mode: "no-cors"
                            redirect: "follow"
                            referrer: ""
                            referrerPolicy: ""
                            signal: AbortSignal {aborted: false, reason: undefined, onabort: null}
                            targetAddressSpace: "unknown"
                            url: "https://code.jquery.com/jquery-latest.min.js"
                            */

                            console.log('request : ', request?.url);
                        }
                    }

                }
            }


            // ------------------------------------------------
            // 🟦 저장된 캐시 정보 삭제 방법
            // ------------------------------------------------     

            // 👉 [특정 파일 삭제]  
            const del_file_result = await cache.delete('https://code.jquery.com/jquery-latest.min.js');
            console.log('del_file_result : ', del_file_result);


            // 👉 [특정 캐시 삭제]  
            /*
            const del_cache_result = await caches.delete('app-cache-v1');
            console.log('del_cache_result : ', del_cache_result);
            // */

            
            // 👉 [전체 캐시 삭제] 
            //*
            const del_cacheNames = await caches.keys();

            for(const name of del_cacheNames){
                const del_cache_result = await caches.delete(name);
                console.log(name, ' / ', 'del_cache_result : ', del_cache_result);
            }
            // */

           
        }
        catch (exception) {
            console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);
        }

    }; 
      
    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

▶️ 569. (javaScript) 자바스크립트 동적 js 파일 추가 및 외부 js 파일 로드 시 타임스탬프 추가해 캐시 초기화 수행 - QueryString 쿼리 스트링 추가

https://kkh0977.tistory.com/8963

https://blog.naver.com/kkh0977/224341759988?trackingCode=blog_bloghome_searchlist


▶️ 7. (TWOK/LOGIC) [모바일] 웹뷰 (webview) 사용 시 로딩 (loading) 속도 향상 및 디스크 캐시 사용 실시

https://kkh0977.tistory.com/2414

https://blog.naver.com/kkh0977/222858889430?trackingCode=blog_bloghome_searchlist


▶️ 64. (Network/네트워크) 쿠키 (Cookie) , 세션 (Session) 차이점 간략 정리

https://kkh0977.tistory.com/7089

https://blog.naver.com/kkh0977/223604703827?trackingCode=blog_bloghome_searchlist


▶️ 49. 크롬 F12 개발자 도구 사용해 로컬 스토리지 , 세션 , 쿠키 저장된 정보 확인 방법

https://kkh0977.tistory.com/1145

https://blog.naver.com/kkh0977/222476096072?trackingCode=blog_bloghome_searchlist


▶️ 53. (Network/네트워크) HTTP Cookie Properties 쿠키 속성 확인

https://kkh0977.tistory.com/4838

https://blog.naver.com/kkh0977/223258113988?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments