Is it possible to dynamically load new content into Handlebars templates using AJAX after the initial content of the page has already been loaded

We are currently revamping a mobile application that offers customers an account dashboard.

The dashboard section of the app relies on numerous web service calls to retrieve data. Previously, we utilized server-side rendering to load the page with available user information at login. Subsequently, we would use AJAX calls to fetch additional data that required backend processing. This approach allowed users to view some information immediately without having to wait for all the data to load entirely.

In our new app, we are contemplating integrating Handlebars. I am aware that it is feasible to populate a Handlebars template using AJAX calls.

Is it viable to mix content that is displayed instantly upon page load with content loaded via AJAX after the initial page load?

For instance, consider the following component:

I aim to have all component content render upon page load, excluding the section highlighted in green. That specific part should be loaded via AJAX post page load. Is this achievable with Handlebars?

Thank you!

Answer №1

If you want to achieve a similar functionality to Stack Overflow using format unicorn, you can follow this example:

Example HTML:

    <div id="messageBox">

    </div>
  </body>
  <script type="text/template" id="templateMessage">
    <h2>{title}</h2>
    <p>{message}</p>
    <br>
    <span><Strong>{sign}</strong><span>
  </script>

Example JavaScript:

String.prototype.formatUnicorn =  function () {
      "use strict";
      var str = this.toString();
      if (arguments.length) {
          var t = typeof arguments[0];
          var key;
          var args = ("string" === t || "number" === t) ?
              Array.prototype.slice.call(arguments)
              : arguments[0];

          for (key in args) {
              str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
          }
      }

      return str;
  };
  var jsonMessage = {title:"Customized Template Using Form Unicorn",message:"Stack Overflow is amazing !!",sign:"John Doe"};
  let myUnicornTemplate = document.getElementById("templateMessage").text;
  var template = myUnicornTemplate.formatUnicorn(jsonMessage);
  document.getElementById("messageBox").innerHTML = template;

Note: You can view a working example with ajax on this jsfiddle link.

I hope this information proves useful! =)

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

Maintain the property characteristics (writable, configurable) following the execution of JSON.parse()

Imagine a scenario where an object is created elsewhere and passed to my module. It could have been generated on the server in node.js, or perhaps in a different module where it was then serialized using JSON.stringify() for transmission (especially if it ...

From NodeJS to full word feature module: Expand all abbreviations to enhance readability!

Is there a way to easily convert abbreviated words to their full form in a string sentence using NodeJS? For Example i'm => I am i've => I have w'ill => we will lets => Let us it's => It is I currently have the gingerb ...

When the Angular script is executed, the variable is not defined

One of my custom directives receives an object named 'vm' in its scope, which contains a property/value pair (ccirCategoryIncidentI : 3) that I need to access. When I try to log this value with console.log(scope.vm.ccirCategoryIncidentI), it init ...

Utilizing phonegap/jQueryMobile to extract OpenCart products in JSON format is a simple process

Looking to retrieve the product catalog in JSON format from my OpenCart store through a phonegap mobile application using Ajax, JavaScript/jQuery. Is this something that can be done with OpenCart? Any suggestions, ideas, or sample code would be greatly ap ...

Tips on using the map and filter methods to narrow down a nested array based on specific object

I am struggling to filter JSON data based on a specific date using Array.Filter and Map. The code I have tried below is not yielding the desired results. Can someone please provide guidance on how to effectively filter JSON data based on a particular date ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Ways to eliminate toggle event in Angular

I've been doing a lot of research online, but all the solutions I find are using jquery. I'm still getting the hang of Angular and Typescript. I found this and this to be unhelpful. I built a monthpicker from scratch, which has a simple and clear ...

Implementing automatic image upload via Ajax without the need for a click event right after selection

I am attempting to upload an image using Laravel with the help of Ajax as shown below $(document).ready(function () { bsCustomFileInput.init(); $('#exampleInputFile').on('change', function(){ var file = t ...

Streaming data from MongoDB to a file using Node.js

Having recently delved into the world of javascript/node.js, I am attempting to accomplish a basic task: connect to MongoDB, convert the JSON response to CSV format, and then write it to a file. My current approach is outlined below: fs = require('fs ...

Is there a way to instruct Express to refrain from parsing the request's query string?

Is there a way to turn off Express's default behavior of parsing query strings and ignore them completely? I parse the query strings on the client side, and receiving a large number of requests with long query strings would be resource-intensive for t ...

Managing data from two tables in Node.js with ejs

I have a question regarding my node.js project that I need help with. As a beginner in this field, I believe the answer may be simpler than anticipated. In my code file named index.js, I found the following snippet after referring to some online documenta ...

What is the most suitable Vue.js component lifecycle for data retrieval?

I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js? ...

Import Socket.io into your Node.js application using the import statement

Can't seem to figure out why I keep encountering this error. Everything works perfectly when I use the request method instead. import express from 'express'; import { createServer } from 'http'; import * as io from 'socket.io& ...

Upon initiating a refresh, the current user object from firebase Auth is found to be

Below is the code snippet from my profile page that works perfectly fine when I redirect from the login method of AuthService: const user = firebase.auth().currentUser; if (user != null) { this.name = user.displayName; this.uid = user.uid; } e ...

A guide to setting up a unit test for an Angular JS controller that utilizes an ajax service

I've been attempting to write unit tests for the code below, but I'm struggling to make it work. Service Code: angular.module('ActivityApp').service('PersonService', [ '$http', function ($http) { v ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

What steps should be taken to modify an image following retrieval of data from the database?

When using the function getDataFromDb(), I am trying to retrieve the latest data from the database. Specifically, I want to use val["id"] as a condition to determine which image to display in the function GetImage. However, my attempts have not been succ ...

Subsequent requests experience delays in processing due to ASP.NET validation errors causing slowdowns

Our usual error logging system, NLog, was not capturing certain application errors. The only way to view these errors was through the Windows Event Viewer, where they appeared as warnings. It appears that the issue stems from a postback triggered by an asp ...