Code: Monitor Page Rendering Time

Chapter 8 - Ajax Optimization

You can use JavaScript to see how long it takes a page to load. For example, at the top of an HTML document, start a script timer:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>And they're off...</title>
<script type="text/javascript">
    var gPageStartTime = (new Date( )).getTime( );
</script>

Then bind a script to stop the timer upon full-page load to calculate how long it took:

window.onload = function ( )
{
    var pageEndTime = (new Date( )).getTime( );
    var pageLoadTime = (pageEndTime - gPageStartTime)/1000;
    alert("Page Load Time: " + pageLoadTime);
}

Of course, instead of alerting the page load time as we did here, we could transmit it to our server with an Ajax request:

sendAjaxRequest("http://example.com/recordtime.php", "time="+pageLoadTime);