IT

자바 스크립트에서 캐시 지우기

lottoking 2020. 5. 27. 07:59
반응형

자바 스크립트에서 캐시 지우기


JavaScript로 브라우저 캐시를 지우려면 어떻게해야합니까?

최신 JavaScript 코드를 배포했지만 최신 JavaScript 코드를 얻을 수 없습니다.

편집자 주 :이 질문은 다음과 같은 장소에서 반복 제되었으며 다음 질문 중 첫 번째 질문에 대한 답이 가장 좋습니다. 이 대답은 더 이상 이상적인 솔루션이 아닙니다.

브라우저가 캐시 된 CSS / JS 파일을 강제로 다시로드하는 방법?

클라이언트가 JavaScript 파일을 새로 고치도록하려면 어떻게해야합니까?

로컬 자바 스크립트 소스 / Json 데이터를 동적으로 다시로드


window.location.reload (true)호출 하여 현재 페이지를 다시로드 할 수 있습니다 . 캐시 된 항목을 무시하고 서버에서 페이지, CSS, 이미지, JavaScript 등의 새 사본을 검색합니다. 이것은 전체 캐시를 지우지는 않지만 현재있는 페이지의 캐시를 지우는 효과가 있습니다.

그러나 최선의 전략은 다양한 다른 답변에서 언급 한 것처럼 경로 또는 파일 이름을 버전 화하는 것입니다. 또한 파일 이름 수정 :?v=n 버전 관리 체계 로 사용하지 않는 이유로 쿼리 문자열사용하지 마십시오를 참조하십시오 .


자바 스크립트로 캐시를 지울 수 없습니다. 일반적인 방법은 다음과 같이 수정 번호 또는 마지막으로 업데이트 된 타임 스탬프를 파일에 추가하는 것입니다.

myscript.123.js

또는

myscript.js?updated=1234567890


JavaScript 파일의 src를 변경해 보시겠습니까? 이것으로부터:

<script language="JavaScript" src="js/myscript.js"></script>

이에:

<script language="JavaScript" src="js/myscript.js?n=1"></script>

이 메소드는 브라우저가 JS 파일의 새 사본을로드하도록합니다.


매시간 또는 매주 캐싱하는 것 외에 파일 데이터에 따라 캐시 할 수 있습니다.

예 (PHP) :

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

또는 파일 수정 시간을 사용하십시오.

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

PHP에서 다음과 같이 매시간마다 코드를 강제로 다시로드 할 수도 있습니다.

<?php
echo '<script language="JavaScript" src="js/myscript.js?token='.date('YmdH').'">';
?>

또는

<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>

이것을 템플릿 끝에 넣으십시오.

var scripts =  document.getElementsByTagName('script');
var torefreshs = ['myscript.js', 'myscript2.js'] ; // list of js to be refresh
var key = 1; // change this key every time you want force a refresh
for(var i=0;i<scripts.length;i++){ 
   for(var j=0;j<torefreshs;j++){ 
      if(scripts[i].src && (scripts[i].src.indexOf(torefreshs[j]) > -1)){
        new_src = scripts[i].src.replace(torefreshs[j],torefreshs[j] + 'k=' + key );
        scripts[i].src = new_src; // change src in order to refresh js
      } 
   }
}

다음은 최신 프로젝트에 사용하는 내용입니다.

컨트롤러에서 :

if ( IS_DEV ) {
    $this->view->cacheBust = microtime(true);
} else {
    $this->view->cacheBust = file_exists($versionFile) 
        // The version file exists, encode it
        ? urlencode( file_get_contents($versionFile) )
        // Use today's year and week number to still have caching and busting 
        : date("YW");
}

보기에서 :

<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">

우리의 게시 프로세스는 현재 빌드의 개정 번호를 가진 파일을 생성합니다. 이것은 파일을 URL 인코딩하고 캐시 버스터로 사용하여 작동합니다. 장애 조치 (failover)로서 해당 파일이 존재하지 않으면 연도와 주 번호가 사용되어 캐싱이 여전히 작동하며 일주일에 한 번 이상 새로 고쳐집니다.

또한 이는 개발 환경에서 모든 페이지로드에 대해 캐시 버스 팅을 제공하므로 개발자는 모든 리소스 (javascript, css, ajax 호출 등)에 대한 캐시를 지우는 것에 대해 걱정할 필요가 없습니다.


또는 file_get_contets를 사용하여 서버별로 js 파일을 읽은 다음 js 내용을 헤더에 에코로 넣을 수 있습니다


이것을 사용해보십시오

 <script language="JavaScript" src="js/myscript.js"></script>

이에:

 <script language="JavaScript" src="js/myscript.js?n=1"></script>

PHP를 사용하는 경우 다음을 수행 할 수 있습니다.

 <script src="js/myscript.js?rev=<?php echo time();?>"
    type="text/javascript"></script>

I had some troubles with the code suggested by yboussard. The inner j loop didn't work. Here is the modified code that I use with success.

function reloadScripts(toRefreshList/* list of js to be refresh */, key /* change this key every time you want force a refresh */) {
    var scripts = document.getElementsByTagName('script');
    for(var i = 0; i < scripts.length; i++) {
        var aScript = scripts[i];
        for(var j = 0; j < toRefreshList.length; j++) {
            var toRefresh = toRefreshList[j];
            if(aScript.src && (aScript.src.indexOf(toRefresh) > -1)) {
                new_src = aScript.src.replace(toRefresh, toRefresh + '?k=' + key);
                // console.log('Force refresh on cached script files. From: ' + aScript.src + ' to ' + new_src)
                aScript.src = new_src;
            }
        }
    }
}

Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:

<?php
    touch('/www/control/file1.js');
    touch('/www/control/file2.js');
    touch('/www/control/file2.js');
?>

...the rest of your program...

It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping.


I tend to version my framework then apply the version number to script and style paths

<cfset fw.version = '001' />
<script src="/scripts/#fw.version#/foo.js"/>

window.parent.caches.delete("call")

close and open the browser after executing the code in console.


Cache.delete() can be used for new chrome, firefox and opera.


Please do not give incorrect information. Cache api is a diferent type of cache from http cache

HTTP cache is fired when the server sends the correct headers, you can't access with javasvipt.

Cache api in the other hand is fired when you want, it is usefull when working with service worker so you can intersect request and answer it from this type of cache see:ilustration 1 ilustration 2 course

You could use these techiques to have always a fresh content on your users:

  1. Use location.reload(true) this does not work for me, so I wouldn't recomend it.
  2. Use Cache api in order to save into the cache and intersect the request with service worker, be carefull with this one because if the server has sent the cache headers for the files you want to refresh, the browser will answer from the HTTP cache first, and if it does not find it, then it will go to the network, so you could end up with and old file
  3. Change the url from you stactics files, my recomendation is you should name it with the change of your files content, I use md5 and then convert it to string and url friendly, and the md5 will change with the content of the file, there you can freely send HTTP cache headers long enough

I would recomend the third one see


You can also disable browser caching with meta HTML tags just put html tags in the head section to avoid the web page to be cached while you are coding/testing and when you are done you can remove the meta tags.

(in the head section)

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0"/>

Refresh your page after pasting this in the head and should refresh the new javascript code too.

This link will give you other options if you need them http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags/

or you can just create a button like so

<button type="button" onclick="location.reload(true)">Refresh</button>

it refreshes and avoid caching but it will be there on your page till you finish testing, then you can take it off. Fist option is best I thing.

참고URL : https://stackoverflow.com/questions/1011605/clear-the-cache-in-javascript

반응형