PHP output buffering is normally enabled by default. In older versions of PHP, a string would be sent to your browser every time the interpreter encountered an echo statement or text outside the PHP delimiters.
Output buffering makes this process quicker and more efficient. The buffer is essentially a big memory-resident string. When text is output, it’s appended to the buffer rather than returned to the browser immediately. The buffer is then “flushed”, i.e. its contents are transmitted and the string is reset pending further output. Flushing occurs when:
- the PHP interpreter reaches the end of the page
- the buffer exceeds the number of bytes specified within PHP’s output_buffering configuration setting, or
- the flush() or ob_flush() functions are called.
There are a few caveats but, assuming it works within your environment, you should consider flushing the buffer immediately after the page’s </head> tag, e.g.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Buffer flushing in action</title> <link rel="stylesheet" type="text/css" href="styles.css" /> <link rel="shortcut icon" href="favicon.ico" /> </head> <?php // flush the buffer flush(); ?> <body> …
(If you’re using WordPress, you could use similar code in your theme’s header.php file.)
Once the browser has received the HTML
head, it can begin to download all linked CSS files, favicons and other resources. These downloads can occur while the browser is idle and waiting for the main
The speed increase will depend on the server-side processing required, the weight of your page, the quantity and size of your CSS files, and whether the browser has cached any resources. However, it’s such a simple optimization, there’s little reason not to do it.
I’d be interested to know whether this technique results in a perceivable speed difference on your website or application.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.
Jump Start Git, 2nd Edition
Visual Studio Code: End-to-End Editing and Debugging Tools for Web Developers