엄지월드

캐시 때문에 css 갱신 안되는 현상 개선 본문

java

캐시 때문에 css 갱신 안되는 현상 개선

킨글 2024. 2. 16. 20:52
반응형

배경 : css를 업데이트했는데, 캐시 때문에 사용자들에게 이전 css가 보여지면서 화면이 깨지는 현상이 있었다. 

 

그래서 방법을 찾아보니 캐시 때문에 css 파일이 갱신이 안되는 경우, 

파라미터를 주게 되면 새로운 파일로 인식하게 되어 새롭게 로딩을 받을 수 있다는 사실을 찾아냈다. 

 

방법은 파일의 수정된 시간에 대한 정보를 읽어와서 파라미터로 주도록 설정하는 코드를 찾아서 적용하였다. 

<!DOCTYPE html>
<html>
    <head>
		<script>
        function getFetchVersion(file) {
            try {
                fetch(file).then(r => {
                    const lastModGmt = new Date(r.headers.get('Last-Modified')); // 마지막 수정일자
                    return fetchCallback(file + '?' + lastModGmt.getTime()); // 파일 이름과 파라미터
                });
            } catch (er) {
                return er.message;
            }
        }
		
        function fetchCallback(path) {
            let link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            link.href = path;
            document.getElementsByTagName("head")[0].appendChild(link); // 태그를 넣음
        }
        getFetchVersion('/src/css/product/product.css');
        </script>
	</head>
	<body>
    	...
    </body>
</html>

 

아래와 같이 깔끔하게 뺄 수 있다. 

<!DOCTYPE html>
<html>
    <head>
		<script th:src="/src/js/common/util.js"></script>
		<script>getFetchVersion('/src/css/product/product.css');</script>
	</head>
	<body>
    	...
    </body>
</html>

'java' 카테고리의 다른 글

DEBUG SMTP: AUTH LOGIN failed  (0) 2022.12.30
java stream 파일 읽기  (0) 2022.12.14
eclipse module import 및 export 방법  (0) 2022.09.30
메서드(Method) 함수(Function) 차이  (0) 2021.03.14
java8 lambda stream 시작하기  (0) 2018.09.01
Comments