What is the best way to store the dom in cache to ensure that the page remains unchanged when navigating back using the back button?

When adding models to my JavaScript application's model collection using AJAX calls, I encounter an issue where if I click on a model and go to the next page, all the loaded models disappear when I hit the back button. What is the most effective way to ensure that the loaded models are preserved across all browsers? Specifically for mobile web. I have been researching solutions such as utilizing bfcache or JavaScript history, but I'm struggling to find a definitive answer. Is there a better alternative approach?

Answer №1

To keep your data easily accessible, consider storing it in local storage and only fetching via ajax when it is not already stored there.

Instead of relying on the standard $.ajax function, you can implement this custom storage-based ajax approach:

function storageBasedAjax(url, cb){

    if (localStorage.getItem("myAxaxCache_"+url)){
      cb(localStorage.getItem("myAxaxCache_"+url));
      return;
    }       

   $.ajax({url: url, success: function(result){
     localStorage.setItem("myAxaxCache_"+url,result);
        cb(result);
   }});
}

Keep in mind to avoid overloading by refraining from using this method with URLs that have changing parameters for each call, as it may overwhelm the local storage capacity.

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

Why is the server displaying a blank white page following the import of Material UI icons/module?

Here is the code snippet I am working on: import React from 'react' import "./Chat.css" import { Avatar, IconButton } from "@material-ui/core"; import SearchOutlinedIcon from '@mui/icons-material/SearchOutlined'; imp ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

Organize information received from a post request into a JSON template

I am attempting to automatically sort information from a post request. Each category is identified by a number (0 -> 1 -> ....) There is one title defined for each category with its respective number, for example: "0": "Are planes fly ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Building a follow/unfollow system in Node.jsLet's create a

I am relatively new to programming and I'm looking to implement a follow/unfollow feature in my application. router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{ user.findById(req.params.id) .then((otherUser)=>{ if(otherU ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Retrieve a specific key value from a dictionary within a Flask function by employing JavaScript

I'm currently working on a feature where a user can input something in a search field, and upon submitting, the script should send a request to a Flask function using JavaScript. The response data should then be loaded accordingly. However, I've ...

What is the optimal method for generating numerous records across various tables using a single API request in a sequelize-node.js-postgres environment?

I need to efficiently store data across multiple separate tables in Postgres within a single API call. While I can make individual calls for each table, I am seeking advice on the best way to handle this. Any tips or suggestions would be greatly appreciate ...

Discovering the significance of a function's scope

I'm a bit confused about how the answer is coming out to be 15 in this scenario. I do understand that the function scope of doSomething involves calling doSomethingElse, but my calculation isn't leading me to the same result as 15. function doSo ...

Issue with conditional comment in IE 8 not functioning as expected

Struggling with changing the SRC attribute of my iFrame specifically for users on IE 8 or older. This is the code I have written: <script> var i_am_old_ie = false; <!--[if lte IE 8]> i_am_old_ie = true; <![endif]--> </script> ...

What is the best way to store an ES6 Map in local storage or another location for later use?

let map = new Map([[ 'a', 1 ]]); map.get('a') // 1 let storageData = JSON.stringify(map); // Saving in localStorage. // Later: let restoredMap = JSON.parse(storageData); restoredMap.get('a') // TypeError: undefined is not a ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

The complete height of the website is concealed by the mobile toolbar/menu

I encountered a perplexing issue regarding the responsive resizing of a website on mobile devices. The problem arises when the full height extends over the toolbar/menu, unless the user manually hides the toolbar. Is there a way to dynamically resize the ...

Transforming an array of HTTP Observables into an Observable that can be piped asynchronously

I am attempting to execute a series of XHR GET requests based on the results of an initial request. I have an array of observables representing the secondary requests I wish to make, and I am able to utilize Array.map for iterating over them and subscribin ...

What are some effective ways to manage errors in Ajax deferred calls?

What is the best way to handle an Ajax deferred error? function CallingApi() { return $.ajax({ url: 'http://localhost:10948/Api/Home/GetEmployee123', contentType: 'application/x-www-form-urlencoded', ...

Using Conditional Rendering and ReactCSSTransitionGroup for Dynamic Animations

I have developed a small application that displays different components based on a Redux state. I am trying to add a "fade" animation when one of the components renders, but unfortunately, it is not working as expected. Here is my current setup: content.j ...