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.
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…
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…
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!