简体   繁体   中英

Measure Image Load Time: PerformanceResourceTiming

I'm trying to measure the speed of the load time of an image (how long it actually takes the image to fully load at full resolution on a user's browser).

I was wondering if the Performance Resource Timing in the window.performance JavaScript was good for doing this, if you recommend it, or if you recommend something else (also preferably JavaScript because I'd like this to be browser-only as I'd like people to test it from different locations as well).

Assuming you have jquery

var startTime = +new Date();
$("#img").attr({"src": imgURI});
var endTime = +new Date();
var finalTime=endTime - startTime;

Alternatively.

var tempImg=getElementById("img");
var startTime = +new Date();
var endTime;
var finalTime;

tempImg.onload = function () {
    endTime = +new Date();
    finalTime=endTime - startTime
}
tempImg.src = imgURI;

Either way it has to be done to an image that is being displayed, not to an in memory image. In memory it will be almost instant. But there is a delay in rendering and DOM recalculations that you would want to factor in to your calculations.

<body onload="loadResources()">
    <script>
        function loadResources()
        {
           var start = new Date().getTime();
           var image1 = new Image();
           var resourceTiming = function() {
               var now = new Date().getTime();
               var latency = now - start;
               alert("End to end qresource fetch: " + latency);
           };

           image1.onload = resourceTiming;
           image1.src = 'https://yourwebsite/Icons/image.png';
        }
    </script>
    <img src="https://yourwebsite/Icons/image_2.png">
  </body>

or

<body onload="loadResources()">
    <script>
       function loadResources()
       {
          var image1 = new Image();
          image1.onload = resourceTiming;
          image1.src = 'https://yourwebsite/Icons/image.png';
       }

       function resourceTiming()
       {
           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].startTime);
              }
           }
       }
    </script>
    <img id="image0" src="https://yourwebsite/Icons/image_2.png">   </body>

Please refer the implementation https://jsfiddle.net/q4euntat/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM