Optimistic rendering

Adam Chernitsky
3 min readJan 21, 2020

When building web applications the most important thing to consider is user experience. If you designed a web app that allowed someone to create something and append it to the page, how joyful would the user experience be if what they created didn’t show up? Or what if the thing they created disappeared after a refresh?

Optimistic rendering is basically tricking the DOM (document object model) into appending something to the page that isn’t actually in the database yet. The main way to do this is by having a form on your web app that someone can use to add something to the page after clicking a submit button. For example on a social media page this could be a post from a user. If you’re using JavaScript to optimistically render something to the page you’d need to create a form in your html with some labels and inputs and you will also need somewhere to put the new data you’re going to be adding to the page. Here’s an example from a project I made:

In my example I am fetching data from a backend that I built myself in rails with endpoints to dogs and breeds. So for my example I had to make a fetch to the backend and then I handled the JSON (JavaScript Object Notation) response and made a function that handles all the rendering:

Now I began building the showDogs function. In this function I used form data for the input fields and you would likely use query selector to grab the form and the container (in this case a section) from your html. Since in this example I’m fetching from the backend, the form data I am fetching is consistent with the names of the attributes from my database. You will also use an event listener to put on your submit button so that when clicked the information that was put in the input fields will be submitted to the page. Generally with a submit event listener you want to use event.preventDefault() to keep the page from automatically refreshing after submission. Since we’re are doing optimistic rendering here it is crucial that you have this or the page will refresh and you will not see what you have just attempted to append to the page. Here is an example of what’s next:

For this specific example with each object being created by the form I wanted to create a div to append the new information to. Inside this div is where you will create some html elements with javascript, and use the form data from the previous picture to manipulate these new elements into displaying what you desire. After that they will be appended to the page:

With this code you will be able to make something appear on the page but it wont survive a refresh. To learn how to make something survive a refresh or persist read one of my other blog posts ‘Fetch Calls and Persisting Data.’

--

--