What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside.

I want to implement a feature where upon deploying a new version of the JAR, I can send a message to the client instructing it to perform a cache-less refresh of all resources.

To serve my SPA, I have a custom HttpServlet that handles URL "rewriting":

private static final Path ROOT = getDevelopmentWebRoot();

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestPath = req.getPathInfo();

    if (requestPath.equals("/")) {
        requestPath = "index.html";
    } else {
        requestPath = requestPath.substring(1);
    }

    Path resource = ROOT.resolve(requestPath);

    resp.setHeader("Cache-Control", "max-age=31536000");
    resp.setContentType(MimeTypes.getDefaultMimeByExtension(resource.toString()));

    try {
        Files.copy(resource, resp.getOutputStream());
    } catch (NoSuchFileException e) {
        Files.copy(ROOT.resolve("index.html"), resp.getOutputStream());
    }
}

My main query is, how can I trigger a cache-less refresh using JavaScript?

Answer β„–1

To implement a cache, include the headers "Last-Modified" and "Cache-Control" with "must-revalidate". This will prompt the browser to send an "If-Modified-Since" request each time.

Next, in your frontend, set up a page reload every X seconds. If nothing has changed, the content will load instantly from the cache. If there are updates, the new page will be loaded.

While I haven't personally tested this method, I believe it should meet your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic variable names in JavaScript can be a powerful tool to enhance

I am currently facing a challenge where I need to generate variables dynamically within a loop. I have been researching different methods, including using the eval(); function, but most of what I found only focuses on changing the value inside an existing ...

Leveraging an HTML interface in conjunction with a node.js application

My objective is to implement JavaScript on the server side. To achieve this, I have decided to use node.js as it seems like the most logical solution. While I am quite familiar with node.js from working on applications, I now need to utilize it for server- ...

Ways to access data from a span within a particular class

When attempting to click on the hospital panel, I encountered an issue. The element contains a class attribute and inner text, and my goal is to click on "εŽδΈ‰". However, I received an error stating "unable to locate element." What mistake might I be mak ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Tips for capturing text input from a Quill rich text editor div

My attempt to retrieve the content entered in Quill editor's editor div using jQuery codes is not proving successful. Although it works for other text inputs, it fails to do so for the editor div. Below is a demonstration of the issue: $(function() ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Matching numbers with the exception of 1 and 0

Is there a way to extract all numbers from a sequence, excluding the first 0 and 1? For example, from 043241.124.22, I want to retrieve 43241.24.22. I've come up with the following code: Pattern p = Pattern.compile("[2-9]"); String[] split = number.s ...

Utilize Node.js and Socket.IO to download a PNG image in a web browser

Looking for assistance in saving an image from Flash to a server using node.js. Below is my code snippet: var pngEncoder:PNGEncoder = new PNGEncoder(); var pngStream:ByteArray = PNGEncoder.encode(bmd); socket.send(pngStream,"image"); Above is the Flash c ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Using Gradle to connect to MySQL using JDBC

I am currently working on a pure Java project that is utilizing Gradle. My main objective is to connect to a MySQL database. Can anyone provide me with step-by-step guidance on what to include in my Gradle build file? I simply want to perform a query to t ...

Modify the values of several dropdown menus (5 in total) at once using jQuery. The values will be dynamically retrieved from a JSON file

https://i.sstatic.net/9vjlz.png Dropdown values for the first dropdown are 1, 2, 3, 4, 5. Dropdown values for the second dropdown are 25, 26, 27, 28, 29. Dropdown values for the third dropdown are 35, 36, 37, 38, 39. The goal is to have each dropdown load ...

The show/hide jquery function is functioning perfectly on desktop devices, but issues arise on mobile devices where the divs overlap each other when using the show() method

I need a way to toggle input text boxes based on selection using a select box This is the HTML code snippet: <div class="row"> <div class="form-group"> <div class="col-sm-1 label2"> <label class="control-label ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

Is there a way to link two HTML files containing jQuery within an HTML index file?

I'm currently working on creating an index page for a pair of HTML files that utilize jquery. Let's break down the structure of these files: Emps1, Emps2: These are two HTML tables that start off empty. TabA_stats, TabB_stats: Each HTML file ha ...

Error in Vue.js: "Trying to access properties of an object that is undefined (specifically '$refs')"

When we trigger methods from a parent component in a child component, we use the following code: await this.$refs.patientinputmask.$refs.patientpersonaldata.ChangePersonalData(); await this.$refs.patientinputmask.$refs.patientaddressdata.SavePersonalAddres ...

Hidden input fields do not get populated by Angular submit prior to submission

I am in the process of implementing a login feature in Angular that supports multiple providers. However, I have encountered an issue with submitting the form as the loginProvider value is not being sent to the server. Below is the structure of my form: &l ...

Chrome is having trouble loading basic JavaScript

Here's the JavaScript code I have placed inside the head tag of my HTML: <script type="text/javascript"> function over1() { var img1 = document.getElementById("1").src; document.getElementById("big").src = img1; } function out() { ...

Developing Modules in NodeJS using Constructors or Object Literals

I am currently developing a nodejs application that needs to communicate with various network resources, such as cache services and databases. To achieve this functionality, I have created a module imported through the require statement, which allows the a ...

Displaying an image gradually as the user moves down the page

Recently, I came across this fascinating website: As you scroll down, the images on the site gradually unveil more details, which caught my attention. This unique effect is not something commonly seen on websites, and I'm curious to learn how it is ...