简体   繁体   中英

Get elapsed time to swap img src using JavaScript

I'd like to get the elapsed time to change the src of an img using JavaScript. Something like the following:

var startTime = new Date().getTime();
document.getElementById('img1').src = someNewUrl;
var elapsedTime = (new Date().getTime()) - startTime;

This code apparently is measuring only the time it takes the browser to set the src attribute of the img.

What I'd like instead is code that will actually measure the time elapsed until the image is actually loaded.

Is there a way I can accomplish that? A solution using jQuery would be delightful.

Thanks.

You need to use onload method to accomplish this. For example

var startTime = new Date().getTime();
document.getElementById('img1').onload = function(){
  var elapsedTime = (new Date().getTime()) - startTime;
}
document.getElementById('img1').src = someNewUrl;

With jQuery

var startTime = new Date().getTime();
$('#img1').load(function(){
  var elapsedTime = (new Date().getTime()) - startTime
).attr({src: someNewUrl});

To elaborate on @Marc's answer (using jQuery and Date.now() for conciseness):

var start = Date.now();

$('#img1').one('load', function()
{
    console.log('Image load took', Date.now() - start, 'ms');
}).attr('src', someNewUrl);

Without jQuery and whatnot:

var img = document.getElementById('img1'),
    start;

img.onload = function ()
{
    var duration = new Date().getTime() - start;
    console.log('Image load took ' + duration + ' ms');
    img.onload = null;
};

start = new Date().getTime();
img.src = someNewUrl;
$('#img1').load(function() {
   ... image has been loaded ...
}

You'd have to have the load handler call another function (or do it itself) to do the elapsed time calculation/display.

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