Force browser to clear cache

后端 未结 17 2087
夕颜
夕颜 2020-11-22 05:04

Is there a way I can put some code on my page so when someone visits a site, it clears the browser cache, so they can view the changes?

Languages used: ASP.NET, VB.N

17条回答
  •  名媛妹妹
    2020-11-22 05:47

    I implemented this simple solution that works for me (not yet on production environment):

    function verificarNovaVersio() {
        var sVersio = localStorage['gcf_versio'+ location.pathname] || 'v00.0.0000';
        $.ajax({
            url: "./versio.txt"
            , dataType: 'text'
            , cache: false
            , contentType: false
            , processData: false
            , type: 'post'
         }).done(function(sVersioFitxer) {
            console.log('Versió App: '+ sVersioFitxer +', Versió Caché: '+ sVersio);
            if (sVersio < (sVersioFitxer || 'v00.0.0000')) {
                localStorage['gcf_versio'+ location.pathname] = sVersioFitxer;
                location.reload(true);
            }
        });
    }
    

    I've a little file located where the html are:

    "versio.txt":

    v00.5.0014
    

    This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a

    location.reload(true);
    

    ...to force reload from server instead from cache.

    (obviously, instead of localStorage you can use cookies or other persistent client storage)

    I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.

    The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).

    I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.

    Hope it helps.

提交回复
热议问题