简体   繁体   中英

Can I load content into Handlebars templates via AJAX after the page has loaded content already?

We are in the process of rebuilding an app that provides an account dashboard to customers.

The dashboard page makes lots of web service calls to get data. In the old app we would use server side rendering to load the page with whatever information we got about the user at login. Then we would make AJAX calls to fill in the stuff that would require a bunch of extra backend calls. This let the user see some info immediately without having to wait for all of the data to come back before they see anything.

We are considering using Handlebars in the new app. I know it's possible to populate a Handlebars template via AJAX.

Is it possible to interleave content that displays immediately on page load with content that is loaded via AJAX after the page loads?

For example, given a component like this:

Imgur

I want for all of the contents of the component to render at page load except for the part in green. That part I want to load via AJAX after page load. Is this something I can do easily with Handlebars?

Thanks!

You can use format unicorn to do what you want like stack overflow does, example:

Your Html:

    <div id="messageLoader">

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

Your script:

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:"Custom Template With Form Unicorn",message:"Stack Overflow Rocks bae !!",sign:"Stan Chacon"};
  let myFirstUnicornTemplate = document.getElementById("templateMessage").text;
  var template = myFirstUnicornTemplate.formatUnicorn(jsonMessage);
  document.getElementById("messageLoader").innerHTML = template;

Edit: Here is jsfiddle working with ajax.

Hope it helps =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM