Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example:

{
"news": [
    {"title": "some title #1","text": "text","date": "27.12.15 23:45"},
    {"title": "some title #2","text": "text","date": "26.12.15 22:35"},
    ...
   ]
}

To display a specific number of these news articles based on a function argument, I am considering implementing pagination. One approach involves slicing the ajax response directly each time the function is called to make a new ajax request.

function showNews(page) {
var newsPerPage = 5,
    firstArticle = newsPerPage*(page-1);
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4) {
        var newsArr = JSON.parse(xhr.responseText),
            ;
        newsArr.news = newsArr.news.slice(firstArticle, newsPerPage*(page));
        addNews(newsArr);
    }
};
xhr.open("GET", url, true);
xhr.send();

Alternatively, I could store all results in newsArr and implement the slicing logic in a separate function like addNews, organized by pages.

function addNews(newsArr, newsPerPage) {
var pages = Math.ceil(amount/newsPerPages), // counts number of pages
    pagesData = {}; 
for(var i=0; i<=pages; i++) { 
    var min = i*newsPerPages, //min index of current page in loop
        max = (i+1)*newsPerPages; // max index of current page in loop
    newsArr.news.forEach(createPageData);
}
function createPageData(item, j) {
    if(j+1 <= max && j >= min) {
        if(!pagesData["page"+(i+1)]) { 
            pagesData["page"+(i+1)] = {news: []};
        }
        pagesData["page"+(i+1)].news.push(item);
    }
}

Which approach would be more efficient? The first method leads to server loading while the second one impacts user memory usage. What choice would you make in this scenario? :)

Thank you for your responses. I appreciate the insights provided, although selecting the best answer proves to be challenging due to the abundance of quality responses.

Answer №1

It seems to be a question that is mostly based on personal opinions.

In my view, using a pagination approach appears more appealing because it avoids any "lag" when displaying the news. This results in a faster loading time from the user's perspective.

Personally, I prefer implementing pagination along with preloading of the next page. By storing the contents of the subsequent page beforehand, there is no delay in displaying it. As soon as a user reaches the last page, the next one can be loaded seamlessly.

Loading all the news at once is certainly not advisable. If there are 1000 news records, every user would have to load them all - even if they do not intend to read a single news piece.

In my view, the principle of less requests == better does not necessarily hold true in this case. There is no guarantee that a user will read through all the news articles. For instance, if StackOverflow were to load all its questions every time the main page is accessed, it would create issues for both StackOverflow and its users.

Answer №2

Given that your service typically returns no more than 1000 records, it is unlikely to cause substantial payload or memory issues based on the type of data involved. Therefore, I believe that option-2 represents the superior choice due to the following reasons:

  • Reduction in the number of service calls required.
  • Improved user experience as there will be no noticeable lag during pagination, enhancing overall site usability.

Answer №3

General guideline:

reducing requests leads to better efficiency

However, there are instances where this may not be feasible. If the data being managed is extensive, you could encounter memory or network limitations, necessitating server-side pagination. Server-side pagination is recommended as the initial approach, with further optimizations like local caching considered only if essential.

It is advisable to test various scenarios to determine their effectiveness in your particular circumstances.

Answer №4

My preference is to retrieve all the data initially, but only display it based on certain conditions. For example, if a user clicks on a "Next" button, the data is already loaded and just needs to be shown or hidden using jQuery.

It's not advisable to make an ajax call every time.

However, it is necessary to fetch new data through ajax if the existing data changes after a certain period of time.

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

AJAX request receives a Flask 404 response

I'm currently facing a challenge in getting my Flask application to properly handle a straightforward AJAX request. The issue seems to be related to sending the request to the correct address. Within my app.py file, I've set up a basic route and ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

Guide on utilizing isElementPresent/isPresent within ng-repeat with Protractor

HTML Code: <div ng-repeat="todo in todos"> <span><input ng-model="todo.title" /></span> <span><input ng-model="todo.time" /></span> <span><input ng-model="todo.name" /></span ...

What is the best way to create a dynamic text area that changes based on a dropdown selection?

I'm trying to create a feature on my form where selecting a retailer from a dropdown menu automatically generates a corresponding link next to the textbox. For example, if someone picks Best Buy, I want a link to bestbuy.com to show up immediately wit ...

Show HTML form elements on the page using jQuery or JavaScript

Is there a jQuery or JS library that can perform the following task: If the user inputs 'x' in A01, then make A01_1 visible. Otherwise, do nothing. <form id="survey"> <fieldset> <label for="A01">A01</label&g ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

Creating a SQL table in Python that can be converted to a JSON object with

Hey there! I need some help converting a SQL query into JSON using Python. I'm running into an issue when trying to use a parameter in the SQL query: Error message: sql syntax error: incorrect syntax near "%" https://i.sstatic.net/1UF8U.png The que ...

Create custom error messages for loopback instead of using the default ones

I am attempting to customize the default error messages provided by loopback. Here is my approach: server/middleware.json: { "initial:before": { "loopback#favicon": {} }, "initial": { "compression": {}, "cors": { "params": { ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

Verify whether the document includes a class that closely matches the provided string using Javascript

I need help identifying elements that include the letters 'ad'. For example: <iframe class="container" /> <!-- Not relevant --> <a class="adp" /> <!-- Relevant --> <a class="adleft" /> ...

Error occurred while retrieving JSON array using Jquery

var groupMembers = $.parseJSON(members); $.each(groupMembers, function (index, item) { $.ajax({ type: "POST", url: "'.base_url(" / panel / listNotifications ").'/'.$id.'/" + valueSelected, d ...

Ensuring Angular applications can effectively run on Internet Explorer

In my Angular application, I have implemented the functionality where users can choose a map to select the delivery point for goods. However, there seems to be an issue with this feature in Internet Explorer (IE) - the map opens but the delivery points ar ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

Using and accessing Ajax response across all routes in an application

I am developing a Node.js Express API application that requires several AJAX calls at the start of the application for global data access in all requests. At the beginning of my app.js file, I include: var users = require('./modules/users'); I ...

Inject a combination of HTML and JavaScript code into the Selenium Webdriver

I am facing a challenge where I have an HTML document stored in memory as a string, and it includes a <script> tag with a script that manipulates the DOM. My goal is to load this HTML page into Selenium WebDriver and retrieve the modified version aft ...

Pass the input array using a jQuery Post request without the need to submit the form

I am looking to send data to a URL without the need to submit a form and reload the page, but my JQuery skills are not very strong. Can someone show me how to achieve something like this in HTML? <input type="text" name="name"> <input type="text" ...

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

Tips for Creating an Animated Progress Bar in a Slider

After implementing jQuery, I managed to create a unique slider on my website. This slider included a thumbnail with captions for each photo. Positioned below the thumbnail was a progress bar fixed in the center between the caption and the image. Users can ...

Using Javascript with the Google Calendar API: How can I swiftly make a new event with the Quick Add feature?

Currently, I am exploring the Google Calendar API and struggling with implementing a Quick Add Event using javascript. Is it possible to achieve this task? Are there any resources or examples that can help me understand how to do it? My issue lies in the ...

Sharing golang gin session with next.js

Utilizing the latest version of Next.js v14.2.3 and App Router. I am currently implementing cookie-based sessions from the gin-contrib documentation, in order to increase a session count. // Backend Golang code snippet ... cookieStore := sessi ...