Make jQuery/AJAX perform instantly on page load

840 Views Asked by At

Is it possible to make content load instantly from AJAX?

For example, on load I use $.getJSON:

$(function(){
  $.getJSON('posts.php',function(data){
    data.posts.forEach(function(post){
       // load info, append divs
    })
  })
 })

There is however a slight delay (maybe 1 second) where the divs aren't appended on page load. Is this only possible if you use PHP on-load?

2

There are 2 best solutions below

0
On BEST ANSWER

The speed of an Ajax call is the speed of an Ajax call. It's a roundtrip to the server so once you've made that roundtrip as fast as it can be on your server, there's nothing else you can do as the rest is just the speed of the transport between your server and the client browser. So, there will always be some sort of delay.

There are some things you can do as a work-around:

  1. You can send the ajax call immediately in the <head> tag rather than waiting for the page to load. When the result comes back, you just store the result. Then, when the page is done loading, you instantly insert the result.

  2. You can hide your main content, run the ajax call, insert the ajax result, then show your content. This will make it all "appear" on screen at once.

The first option would look like this:

<head>
  <script src="jquery.min.js"></script>
  <script>
  $.when($.getJSON('posts.php'), jQuery.ready).then(function(result) {
      // result[0] is the result from the getJSON call
      // and the DOM is ready so you can insert the content here
  });
  </script>
</head>

This starts the ajax call immediately as the page starts to load to get it started as soon as possible. Then, when both the ajax call is done and the DOM is ready, you can insert the content.

2
On

This is more of a UX issue. What you can do is make it "perceived" as instant. For example, does it have an Ajax loader? Can you fade in the content when ready? There are lots of tricks you can do to make it "instant". I do agree, you can't just randomly pop stuff into the page. That can frighten people.