开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜