Speeding up Initial Rendering of Rails Pages with render_async

Nikola Đuza

Novi Sad, Serbia

Software Engineer @ Toptal

Open source contributor

Novi Sad JS Organizer

https://nikolalsvk.github.io/

Nikola Đuza

Novi Sad, Serbia

Software Engineer @ Toptal

Open source contributor

Novi Sad JS Organizer

https://nikolalsvk.github.io/

/nikolalsvk

/nikolalsvk

/nikolalsvk

/nikolalsvk

Nikola Đuza

Novi Sad, Serbia

Software Engineer @ Toptal

Open source contributor

Novi Sad JS Organizer

https://nikolalsvk.github.io/

πŸπŸ’¨ Rails is FAST πŸŽπŸ’¨

Rails is FAST❓

Let's PROVE it

by building a website

Let's PROVE it

SHOW page

/movies/1

Lets add some ratings

SHOW page

/movies/1

🐌 Rails is SLOW πŸ›΅

It can't be

🐌 Rails is SLOW πŸ›΅

🐌 Rails is SLOW πŸ›΅

WE MADE IT SLOW

SHOUT OUT TO

YOU'RE NOT SLOW ❀️

ANYWAYS

LET'S OPTIMIZE THIS ASAP

WE'RE GOING TO USE render_async

WHY render_async❓

INTERNET POINTS

REPLACE THIS INSIDE

app/views/movies/show.html.erb

STEP #1

WITH THIS

app/views/movies/show.html.erb

STEP #1

config/routes.rb

STEP #2

STEP #3

REMEMBER THIS

app/views/movies/show.html.erb

LET'S PUT IT INSIDE

app/views/movies/_rating.html.erb

STEP #4

ADD content_for TO

app/views/layouts/application.html.erb

STEP #5

INITIAL PAGE LOAD

REDUCED FROM

4s to 24ms

BUT THE USER STILL SEES THIS

LET'S ADD A PLACEHOLDER

app/views/movies/show.html.erb

HOW DOES IT WORK❓

2 PARTS

1. Rails

2. JavaScript

VIEW HELPER

  • defines render_async view helper πŸ“

  • makes it available in views πŸ‘

  • passes all the arguments to render_async partial πŸ›‚

render_async PARTIAL

  • sets up neccessary HTML elements πŸ—

  • puts a placeholder πŸ“­

  • passes arguments of render_async call to JS part 🀝

LET'S BREAK IT DOWN

ADD content_for TO

app/views/layouts/application.html.erb

STEP #5

2 PARTS

βœ… 1. Rails

2. JavaScript

JavaScript part

  • makes a request to a path that we passed to render_async πŸš€

  • inserts request response to a page where we put render_async πŸ›¬

2 PARTS

βœ… 1. Rails

βœ… 2. JavaScript

NOW THIS MAKES SENSE

HOW DOES IT WORK❓

  • It loads partials asynchronously from the server

  • renders them on the page

LET'S PIMP OUR DVD WEBSITE

LET'S ADD RATINGS ON INDEX PAGE

app/views/movies/index.html.erb

app/views/movies/index.html.erb

YOU CAN DO OTHER THINGS WITH render_async

ADD SOME STYLING πŸ’…

ADD ERROR HANDLING πŸŒ‹

OTHER FEATURES

  • Polling πŸ”ƒ

  • Caching πŸ’½

  • Event dispatching πŸŽ†

  • Toggling πŸ‘†

USE render_async TO:

  • Optimize initial page load

  • Some action is doing too much and it's slow

  • It has a tendency to fail and block the whole page

  • You need to poll for changes

Бпасибо!