简体   繁体   English

获取使用JavaScript交换img src所用的时间

[英]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. 我想获得使用JavaScript更改img的src所花费的时间。 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. 这段代码显然只是测量浏览器设置 img 的src属性所花费的时间。

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. 使用jQuery的解决方案将是令人愉快的。

Thanks. 谢谢。

You need to use onload method to accomplish this. 您需要使用onload方法来完成此任务。 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 用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): 详细说明@ Marc的答案(使用jQuery和Date.now()来简洁):

var start = Date.now();

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

Without jQuery and whatnot: 没有jQuery和诸如此类的东西:

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. 您必须让加载处理程序调用另一个函数(或自己执行)来执行经过时间计算/显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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