Skip to content
Advertisement

Lazy loading for WordPress external api get request

I have an endpoint that takes a long time (about a minute) to give a response. I want to call this endpoint from a WordPress website while wp_remote_get and wp_remote_retrieve_body are running in the background, but I always get the page loaded only after the request is finished.

Is there a way I can add some lazy process so that the page can be displayed and the user gets a ‘loading, please wait..’ message until the request content is retrieved? I have seen many methods for image lazy loading but not for an arbitrary php run in the server. I also want to hide the get url from the page source script, all js get solutions seem to expose the url requested.

Advertisement

Answer

Here’s what you need to do.

  1. Create your page — maybe in your template — with some placeholder text. Something like this might work:

    <div id="jimmys-lazy-loading">
      loading, please wait...
    </div>
    
  2. Extend the WordPress REST API by adding a custom endpoint to the code you’re writing (your plugin or theme customizations, maybe). When you hit this REST endpoint from your web page, it will in turn hit that slow endpoint, retrieve the data, and return it.

  3. Write some Javascript that hits your REST API and then replaces your placeholder text with the stuff that you got back.

Or, if your slow endpoint allows itself to be hit directly from your users’ browsers, write your Javascript to hit it and replace the placeholder text.

Once you get the basics working, you can make a fancier “wait” display, maybe with a spinner.

It’s hard to give more specific advice without knowing a bit more about what you hope to do. Don’t hestitate to ask another question if you still need help.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement