我试图获取每个 iframe 的加载时间,然后显示时间。这是我当前拥有的代码(没有加载时间计算):
<iframe id="1" width="100" height="100" src=""></iframe>
<script type="text/javascript">
$(document).ready(function(){
var array = ['http://www.example1.com', 'http://www.example2.com', 'http://www.example3.com'];
$('#1').on('load', function() {
$('#1').attr('src', array.pop());
}).attr('src', array.pop());
});
</script>
它将数组中的链接放入 iframe 中,依次加载每个 iframe。
这就是我之前获取加载时间的方法:
<script type="text/javascript">
beforeload = (new Date()).getTime();
function pageloadingtime(i)
{
var afterload = (new Date()).getTime();
var seconds = (afterload-beforeload)/1000;
document.getElementById("loadingtime"+i).innerHTML = seconds;
}
</script>
这个方法对我来说不起作用,因为它同时加载了所有 iframe,而不是一个一个地加载。
如何在第一个代码中使用第二个代码方法来计算和显示 iframe 的加载时间?
最佳答案
这个怎么样:
$(document).ready(function(){
var array = ['http://www.example1.com', 'http://www.example2.com', 'http://www.example3.com'];
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
$('#1').on('load', function() {
loadTimes.push((new Date()).getTime());
$('#1').attr('src', array.pop());
if (array.length === 0) {
$.each(loadTimes, function(index, value) {
alert(value - beforeLoad);
});
}
}).attr('src', array.pop());
});
旁注
您必须确保可以通过 iframe 访问正在检查的网站,因为现在大多数网站都不允许使用 iframe。
如果您仍然想在没有 iframe 的情况下测量负载并使用 javascript,您也许可以使用 $.get
请求来模仿同样的事情。
关于javascript - 获取具有多个源的每个 iframe 的加载时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15052549/