简体   繁体   中英

How do you properly handle caching static web content?

Browsers cache static files. It's what they're designed to do. 99% of the time, that's a good thing. Until we as developers update that static content.

If a developer updates a javascript file, but a user's browser pulls the cached version of it, then:

  • Best case, it'll be missing some new functionality until the browser decides to update its cache
  • Worse case, if you also updated the html page to call a javascript function that didn't exist in the older version of the javascript file that the browser cached, your page breaks

As developers, we know to hit Ctrl+Shift+R, or Ctrl+F5, or open dev console, disable cache on the Network tab, and reload. But users don't know that.

What is the best practice to handle updates to static content?

  • Is it to make sure that when you add new functions to a .js file, you push out the update to production a few hours/days before you update the html to call that function in <script> tags, allowing browsers to updated their cache over that time?
  • Is it to not call javascript functions from HTML within <script> tags at all?
  • Is there a way to somehow force browsers to expire cache on a specific static file when you update it?
  • Something else?

Obviously disabling all caching on your site is possible, but not a realistic solution.

PS. I'm not using any kind of frontend framework - just raw javascript/jquery. If the situation is different with frontend frameworks, I'd love to heard about that too at a high level

If I understand correctly, you want the JavaScript file to be updated for the user when you update. you should use service work API to create a cache version for specific files or use the Google workbox library. click here . for service worker API click here

Some years ago location.reload(true) allowed bypassing the cache like CTRL / Command + Shift + R does. Only Firefox continues to support this feature by now, but the hard reload using javascript is no longer supported on chromium based browsers. ( spec doesn't describe this feature (anymore) )

jQuery uses a simple workaround to be compatible with almost everything. If you load something with jQuerys jQuery.ajax({ url, cache: false }) , it appends a _=TIMESTAMP parameter to the url, which has a similar effect but may bloat the cache.

You can make use of the Entity tag header ( ETag ). Entity tags are similar to fingerprints and if the resource at a given URL changes, a new Etag value must be generated by the server, which is a similar behavior to the Last-Modified header. ( caniuse:etag )

It is also possible to clear the sites cache with a Clear-Site-Data: "cache" header. ( mdn , caniuse:clear-site-data )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM