How to implement caching using XMLHttpRequest?

As someone who has primarily relied on jQuery's AjAX method, I am relatively new to using XMLHttpRequests. However, due to performance concerns in a web worker environment, I now find myself having to resort to the classic XMLHttpRequest.

Currently, I am attempting to reconstruct the cache property from jQuery. In instances where I need to disable caching, I have implemented the following:

xhr.setRequestHeader("Cache-Control", "no-cache");

However, I am unsure about which header I should set if my intention is to enforce caching instead of preventing it. Any suggestions?

Answer №1

When making a request, you have the option to include the max-stale parameter in the Cache-Control header. According to the information provided in RFC 7234:

The max-stale directive allows the client to accept a response that has exceeded its recommended freshness period. If a value is specified for max-stale, the client accepts a response that is not older than the given number of seconds beyond its freshness lifetime. On the other hand, if no value is assigned to max-stale, the client is open to accepting any stale response regardless of its age.

Answer №2

There exist several options for setting headers to promote caching, however, these headers (including Cache-Control, which you are utilizing incorrectly) happen to be response headers that need to be dispatched from the server rather than request headers.

An illustrative instance of implementing Cache-Control:

Cache-Control: max-age=7200

This Caching Guide for Web Content Creators and Administrators provides in-depth coverage on this topic.

Answer №3

Take a look at this resource for information on how to effectively cache static assets.

Consider using the following cache control directive: Cache-Control: public, max-age=604800, immutable

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

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

What is the best way to retrieve the image name and image type when uploading them through the Froala editor

After uploading an image using Froala Editor, I encountered a problem where I couldn't retrieve the image name and type in ajax. I needed to find a way to transfer that file to my own server with Laravel. Here is the code snippet for the ajax part: ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

Encountering HTML content error when attempting to log in with REST API through Express on Postman

I'm currently in the process of developing a basic login API using Node.js and Express. However, I've encountered an error when testing with Postman: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Managing promises - updating database entry if it already exists

I'm encountering a new challenge with Promises. Objective: Update the database entry only if P_KEY exists. The current database is accessible through a module that has both get and put methods for the database, each returning a Promise. Approach: ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

Toggle class on child element when parent is clicked

I am currently working on a functional React component that looks like this: const RefreshButton = () => ( <IconButton> <RefreshIcon /> </IconButton> ) My goal is to dynamically assign a class attribute ...

The absence of the Ajax Template in Rails 4 is causing a setback

While practicing, I attempted to add a basic message form with an Ajax call. However, I encountered an error indicating that a template is missing. The error seems to be related to the Devise gem and reads as follows: Missing template messages/create, app ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Having Trouble with Shopify's Asynchronous Ajax Add to Cart Feature?

I have developed a unique Shopify page design that allows users to add multiple items to their cart using Shopify's Ajax API. I've created a test version of the page for demonstration: Below is the current javascript code I am using to enable as ...

Tips for implementing the quill-image-drop-module with Vue 3

I am currently utilizing the vueup/vue-quill package for Vue 3 and I would like to incorporate the kensnyder/quill-image-drop-module. This is the snippet of my code: Main.js import { QuillEditor } from '@vueup/vue-quill'; import '@vueup/vu ...

Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({ Id: Joi.number().required(), CustomerName: Joi.string() .trim() .required() .when('$isInValidCustomer', { i ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...