What is the best way to preserve the scroll location when revisiting a page with lazy loading enabled?

My question is quite straightforward, just like the title suggests. I am looking to implement a feature similar to Twitter's behavior where when users navigate away from a page and return using the browser's back button, they are taken back to where they left off. How can I achieve this functionality in Django? It may be worth mentioning that my project utilizes Vue as a cdn.

I can provide an example to clarify my query. On macOS computers running Safari or Chrome browsers, pressing the back button on the browser results in the desired action. It appears as though the previous page was cached and seamlessly reloads. However, on Windows or Linux computers, pressing the back button triggers a full request for the previous page instead of reloading it from cache.

Answer №1

If you are utilizing views to display your entire page, it may be challenging to find a simple solution for browser scrolling on the back button.

When using templates in HTML/CSS/JavaScript, you have two options: either rely entirely on the browser to handle scrolling (which works when the page is cached by the browser) or implement a script that saves previous and current routes in local storage and checks scrolling upon page load:

const storedRoutes = localStorage.getItem("routes");
const currentPath = window.location.pathname;
let newPreviousRoute = null;

if(storedRoutes) {
    const routes = JSON.parse(storedRoutes);
    const isPreviousRoute = routes.previous != null
             && routes.previous.path === currentPath;

   if(isPreviousRoute){
       const { x, y } = routes.previous;
       window.scrollTo(x,y);
   }

   newPreviousRoute = routes.current;
}

const newRoutes = {
    current: { x: 0, y: 0, path: currentPath },
    previous: newPreviousRoute
}
localStorage.setItem("routes", JSON.stringify(newRoutes));

Include this script on the load of each page. Additionally, add a listener on beforeunload to capture the last scroll position:

const xScroll = window.pageXOffset 
      ?? document.documentElement.scrollLeft 
      ?? document.body.scrollLeft 
      ?? 0;
const yScroll = window.pageYOffset 
      ?? document.documentElement.scrollTop 
      ?? document.body.scrollTop 
      ?? 0;
let updatedRoutes = JSON.parse(localStorage.getItem("routes"));

updatedRoutes = { ...updatedRoutes, current: { ...updatedRoutes.current, x: xScroll, y: yScroll } };
localStorage.setItem("routes", JSON.stringify(updatedRoutes));

Keep in mind that this method will enforce scrolling even when a link on your page redirects to the previous one.

Addition: If you're considering using a frontend framework like Vue with Vue Router, you can simplify this process by utilizing <router-link> for navigation within your website, as scrolling will be handled automatically. Check out this feature in the documentation. A similar approach is used by Twitter, as seen here where they employ React Native for web.

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

Tricks for disabling _blank behavior in jquery?

I'm currently integrating a widget into a webpage using PHP. The widget contains jQuery code that causes all links to open in an external page. Is there a way to override or disable this code so it doesn't impact every link on the page? My prefe ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Experiencing a div overflow issue with Google Chrome when the page initially

My jQuery script resizes all divs within a container, but I'm facing an issue in Google Chrome when I reload the page. If I resize the browser width and refresh the page, the divs resize but the text overflows the boxes. How can I solve this problem? ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Having trouble accessing the latest version of the ReactJS single page application in Chrome

Our application is built on ReactJS and deployed using S3 and CloudFront. We are experiencing an issue where clients often need to perform a hard refresh of the web app to access the latest Single Page Application (SPA). In order to address this problem, ...

Tips for synchronizing the indexes of two arrays using a common value in JavaScript

Is there a way to sort one array to match the order of another array with identical content, based on a shared property? For instance: let firstArray = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // always in this order let secondArray = [{id: 456, . ...

Automatically navigate the user to a different webpage in Node.js upon completion of a function within a POST request

I have a nodejs script where the user starts at localhost:3000/index. When the code runs, the page /index displays a form. Upon clicking the submit button, the user is redirected to localhost:3000/process. In the script.js file, there is a POST request tha ...

Sending data through ajax to PHP on separate pages is a common practice

Here is where I choose my preferred option Company Name<br /> <select id="company" name="selected"> <option value="">Option A</option> <option value="">Option B</option> </select> When I click this, a mo ...

The ngClass directive did not expect the token '=='

Hey everyone, I'm currently facing an issue while trying to use multiple expressions in my ng-class directive. Unfortunately, the browser console is throwing this error: Error: [$parse:syntax] Syntax Error: Token '==' is unexpected, expecti ...

Three Js is unable to identify OBJLoader

Seeking assistance to resolve an error message while attempting to load a 3D Model in Three.js. Unable to find any information online about this issue. Can anyone provide guidance? I have confirmed that the mtl and obj libraries are being called in the co ...

A guide on extracting and converting strings in React to display as HTML

I am in the process of developing a simple blog app using a MERN stack. Currently, I have the functionality to create posts with just plain text. Is there a way to incorporate HTML rendering within the content of these posts? For example, a post might con ...

One method to retrieve the id from the database when the button is clicked using ajax

In this particular scenario, I am working on a message thread that is inside a modal. The objective is to display a message thread for a specific individual based on their reference number. However, I am encountering an issue in passing the reference numbe ...

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

Obtain the Key with the Greatest Value from a JSON Object

I'm currently working with data fetched from an API response in an attempt to identify the pitch with the highest speed. Below is a snippet from the API response. { page: 1, total_pages: 4, listings: [ { name: "Zack Greinke", pitc ...

Having trouble retrieving response headers in Angular 5

After sending a post request to a server, I receive a response with two crucial headers for the client: username and access-token. The Chrome debug tool's Network Tab displays the data from the response like this: https://i.sstatic.net/XN9iv.png In ...

Experiencing difficulties with implementing jQuery validate for form submission, specifically when utilizing ajax within the submitHandler() function

I have a form that I am validating with jQuery validate plugin and want to submit it using ajax. However, when I place the ajax call inside the submitHandler() function of the validation method, the browser hangs. Can anyone help me figure out what's ...

Ways to detect when the user begins typing?

There is an input box with a cross icon that clears the input when clicked. The icon is visible even when the box is empty, which may not make sense. It would be better to show the icon only when the user starts typing. How can I detect when the user start ...

JavaScript: XHR struggles with managing multiple asynchronous requests

Hey there, I'm currently attempting to access a single resource multiple times with various parameters. Here's what I have so far: Essentially, I am making requests for the following domains: var domains = [ 'host1', 'host2&apos ...

Combining httpProvider responseInterceptor with $http error callback does not function properly

In my application, I implemented a "loading screen" feature inspired by this post: 'Click' However, I am facing an issue where all $http requests are triggering the "success" callback, even for URLs that do not exist. $http.post("this doesnt ev ...

What is the best way to store information in a React Native app for future use?

Can anyone assist me in developing a React Native application that is capable of storing data locally and then synchronizing it with the server? I would greatly appreciate any guidance on how to achieve this. ...