Force browser to clear cache

后端 未结 17 2116
夕颜
夕颜 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 06:03

    Update 2012

    This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.

    In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache() can be used to update the cached version of your website without the need for manually reloading the page.

    This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:

    // Check if a new cache is available on page load.
    window.addEventListener('load', function(e) {
    
      window.applicationCache.addEventListener('updateready', function(e) {
        if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
          // Browser downloaded a new app cache.
          // Swap it in and reload the page to get the new hotness.
          window.applicationCache.swapCache();
          if (confirm('A new version of this site is available. Load it?')) {
            window.location.reload();
          }
        } else {
          // Manifest didn't changed. Nothing new to server.
        }
      }, false);
    
    }, false);
    

    See also Using the application cache on Mozilla Developer Network for more info.

    Update 2016

    Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.

    Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:

    This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.

    So does Using the application cache on Mozilla Developer Network that I referenced in 2012:

    Deprecated
    This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

    See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.

提交回复
热议问题