Drastically Speed Up WordPress with Progressive Loading

What is progressive loading?

“Progressive loading” can mean many different things. Generally, it means partially loading something first, then loading the rest later. In this article, “progressive loading” refers to loading HTML in chunks. PHP uses buffers to improve efficiency. Buffers batch up PHP output so your server can send fewer responses. Without buffers, your server would have to send a response each time PHP generates output (e.g. by calling echo). Each response carries a lot of overhead, so it’s usually faster to temporarily store all the output in a buffer. When your entire PHP script finishes running, your server sends the buffer content to the browser. The total response time is shorter with buffers, but there are consequences. Browsers won’t receive any data until the entire PHP script finishes running. This means your browser has to wait until PHP finishes before downloading any resources (e.g. styles, scripts, or images). Your page would load faster if you could parallelize running the PHP script and downloading resources. This is what progressive loading can do.

Benefits of progressive loading

Here’s how it looks like to load a WordPress page with buffering:

Chrome devtools network tab
Loading resources without progressive loading

The green part is mostly waiting for PHP to run. As you can see, the styles and scripts don’t start downloading until PHP finishes running. With progressive loading, browsers can start downloading resources much earlier:

Chrome devtools network tab
With progressive loading

The styles and scripts started downloading in half the amount of time. Since downloading styles and scripts blocks rendering, this makes rendering the page a lot faster. The total time it took for the document to load is slightly longer, but we save time by loading everything else sooner.

Implementing progressive loading in WordPress

The simplest way to do progressive loading is flushing the buffer in strategic places. If you flush the buffer after generating <head>, browsers can start downloading the styles and scripts in the <head>. In WordPress, a lot of processing happens after the entire <head> is generated. We can save a lot of that time by parallelizing using progressive loading. Here’s the code to flush the buffer right before </head>. You can put it in your functions.php:

add_action('wp_head', function() { ob_flush(); flush(); }, 999);

If you’re comfortable with PHP, you can improve this by moving some resource-intensive processing to after do_action(‘wp_head’);. For example, some themes use rel=”prev” and rel=”next”, which can take a relatively long time. You can move those lines to after do_action(‘wp_head’);. There’s a lot more optimization you can do with progressive loading. Have fun speeding up your blog!

We will be happy to hear your thoughts

      Leave a reply

      Login/Register access is temporary disabled