Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attitude/6670139 to your computer and use it in GitHub Desktop.
Save attitude/6670139 to your computer and use it in GitHub Desktop.
Faster page loading by closing connection early and deferring processes to finish only after that

Page Speed Tip: Defer time consuming processes after sending the page output

Recently I have written a PHP class to try server analytics. But using the UAMP, script has to wait for response from Google's servers in order to close the connection. Even if the response took less than 100ms, still it's unnecessary time for client to wait and show loading spinner and block page render.

There is a space for optimisation: closing connection early and present the client with the response before the script finishes it's run.

1. Store output to a buffer

Edit the beginning of the script file handling the request:

<?php

// (optional) Remember when the execution started
$time_start = microtime(true);

// Begin the Ouput Buffering
ob_start();

// Handle the request…

2. Close the connection and continue execution

By sending Connection: close header browser can free the connection and by Content-Lenght header you are telling the browser what response to expect. Only after it has received the output of specified length, it can close the connection and continue with rendering of the page and sending other requests.

// Calculate the content length
$size = ob_get_length();

// Set headers
header("Content-Length: $size");
header('Connection: close');

// (optional) Send some execution time info
header('X-Response-Time: '. number_format((microtime(true) - $time_start) * 1000, 1).' ms');

// A rather hacky (but working) way to echo the output
ob_end_flush();
ob_flush();
flush();

// Finish writing to the session files to release it for upcoming requests
if (session_id()) {
    session_write_close();
}

// Extra processing comes here…

Conclusion

You can use this technique to defer additional writing to tables, sending some mail notifications, pinging other servers, heavy-lifting calculations or (as me) sending server analytics.

Let me know how you used this technique, how it worked for you.

Have fun!

@martin_adamko

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment