hey guys am trying to implement this php script which displays how long my web page takes to load in seconds the code is two parts. this first part goes at the beginning of the web page <? $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; ?> then the final part, that echos the number of seconds it took to load the page goes at the end of the web page <? $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); echo '<p>Page generated in '.$total_time.' seconds.</p>'."\n"; ?> the entire script works fine, but the problem i am having is that the time gets displayed only at the end of the web page where the echo code was placed but instead i would like to have it echo the results at the top of the page instead of the end i tried to put it in a function but it didn't work out any ideas would be greatly appreciated
Use the output buffering functions, which let you modify the final page before rendering. The first code comment contains an explanation of what's going on. <?php /* this function is called when the output is ready to be flushed to the browser. We calculate our page creation time and substitute it into a string on our web page. For this example, we look for the string ### and substitute that. */ function ob_buffer_callback($buffer) { global $start; // hacky, but necessary $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); // replace our time placeholder with the actual value return (str_replace("###", $total_time, $buffer)); } // calculate start time $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; // start buffering output ob_start(ob_buffer_callback); ?> <html> <head> </head> <body> <p>Page loaded in ### seconds</p> <p>More content</p> <div>Maybe a div too</div> </body> </html> <?php ob_end_flush(); ?> PHP:
If the user does not have Javascript enabled (a small percentage do, but it is still a possibility) then the page load time will not be displayed at all. This is not good. CSS is a styling language, you can't calculate stuff like loading times with it.
For this problem the only thing CSS can provide is the ability to potentially set the display type to none until the page is finished loading, then you can use javascript to unhide it when the page is finished. That would be a viable javascript approach. Your page might have a paragraph with an id of "pageRenderTime" and the css for that is display: none and the tag is empty. After your entire page loads have javascript set the display back to inline once you've set the render time information.