Friday 20 November 2015

Calculate loading time of page using javscript

Introduction:

          I am going to explain here how to calculate  page loading time using javascript with help of time function.

Explanation:

Here i calculated before loading and after loading time of page then i reduced time from after loading to before loading,here i used "(new Date()).getTime() " function for calculating time.

I hope you  understand from below code:

Calculate before lading time:

beforeload = (new Date()).getTime();

Calculate after loading time:

afterload = (new Date()).getTime();


now use the beforeload and afterload to calculate the seconds

secondes = (afterload - beforeload) / 1000;

Complete code for calculating page loading time:

<script language="javascript"  type="text/javascript" >
//calculate once started page 

 beforeload = (new Date()).getTime();
    function calculatepageloadingtime() {
        //get time after loaded the page
        afterload = (new Date()).getTime();
        // now use the beforeload and afterload to calculate the seconds
        secondes = (afterload - beforeload) / 1000;
        // If necessary update in window.status
        window.status = 'You Page Load took  ' + secondes + ' seconde(s).';
        // Place the seconds in the innerHTML to show the results
        document.getElementById("loadingtime").innerHTML = "<font color='red'>(You Page Load took " + secondes + " seconde(s).)</font>";
    }
   window.onload = calculatepageloadingtime;
    </script>


Here i used  <div> tag to display loading time
so i created div tag with id is "loadingtime" as below code

<div id="loadingtime"></div>

i used to get div tag id from javascript function as below code

document.getElementById("loadingtime").innerHTML = "<font color='red'>(You Page Load took " + secondes + " seconde(s).)</font>";
 

No comments:

Post a Comment