【问题标题】:JS - readAsDataURL blocks browser activityJS - readAsDataURL 阻止浏览器活动
【发布时间】:2013-05-06 05:19:35
【问题描述】:

当我将文件加载到浏览器中时,我想向用户显示动画加载 gif。但是如果文件很大,浏览器看起来很忙,我的 gif 动画就不起作用。我可以做些什么来可视化加载?

HTML

<img id="loader" src="img/load.gif" />

JS

reader.readAsDataURL(file);
reader.onloadend = function(){
    document.getElementById('loader').style.display='none';
    var source = reader.result;
    document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';

【问题讨论】:

  • 你为什么删除你的previous question 并在一分钟后重新发布同样的问题?
  • 我无法编辑标题,抱歉我很笨拙

标签: javascript html file-upload


【解决方案1】:

理论上,您所拥有的应该可以工作,因为读取操作是异步的。也许是阻塞执行的 onloadend 回调。无论如何,你可以试试这个:

reader.onloadend = function(){
    document.getElementById('loader').style.display='none';
    var source = reader.result;
    document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';
// Make sure to start loading only after the loader was displayed
// (give the browser a chance to repaint)
setTimeout(function() {
    reader.readAsDataURL(file);
}, 40);

【讨论】:

  • thanx,我检查了一下,gif是动画的,然后在加载开始时停止
  • 我怀疑瓶颈是将一个巨大的数据 URL 加载到一个 img 元素中。尝试改用画布。
  • 当我使用画布时它也静止不动,但加载速度更快
【解决方案2】:

加载的事件应该首先被钩住。试试这个:

reader.onloadend = function(){
    document.getElementById('loader').style.display='none';
    var source = reader.result;
    document.getElementById('img').setAttribute( 'src', source);
}
reader.readAsDataURL(file);

document.getElementById('loader').style.display='block';

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2015-09-06
    • 1970-01-01
    • 2012-04-16
    • 2019-11-09
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多