how to calculate image loading/rendering time in javascript?

Is there any way to find image loading/rendering time in a webpage using javascript/jquery?

Answers:

Answer

The right answer here is to use the development tools built into a browser like Chrome or Firefox/Firebug that will tell you how long all resources in the page are taking to load. Those tools have access to more information that pure javascript has access to.

With javascript, you can precisely time the loading of an image that is specified with javascript. You cannot use javascript to precisely time the loading of an image that is specified in your HTML because there is no precise way to start a javascript time measurement at exactly the instant that the image starts loading.

To time an image specified in javascript:

var startTime = new Date().getTime();
var img = new Image();
img.onload = function() {
    var loadtime = new Date().getTime() - startTime;
    console.log("image took " + loadtime + "ms to load");
};
img.src = "http://www.whatever.com/testimg.jpg";

The best you could do for an image specified in HTML would be this:

<script>
var startTime = new Date().getTime();
function doneLoading() {
    var loadtime = new Date().getTime() - startTime;
    console.log("image took " + loadtime + "ms to load");
};    
</script>
<img src="http://www.whatever.com/testimg.jpg" onload="doneLoading()">

The <script> tag in the previous example would need to be immediately before the <img> tag.

But seriously, use the development tools in Chrome or Firebug and you can see exactly how long all page resources are taking to load.

Answer
var resourceList = window.performance.getEntriesByType("resource");
           for (i = 0; i < resourceList.length; i++)
           {
              if (resourceList[i].initiatorType == "img")
              {
                 alert("End to end resource fetch: "+ (resourceList[i].responseEnd - resourceList[i].responseStart ));
              }
           }

https://jsfiddle.net/q4euntat/5/

You can refer the link above, Implemented it on jsfiddle.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.