2013-05-11 108 views
3

当我将一个文件加载到浏览器中时,我想向用户显示一个动画加载gif。但是,如果文件非常大,浏览器看起来很嘈杂,那么我的gif动画就不起作用了。我可以做什么来可视化加载?JS - readAsDataURL阻止浏览器活动

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'; 
+0

为什么你删除[前一个问题(http://stackoverflow.com/questions/16499969/js-readasdataurl-blocks-animated-gif)和刚刚重新发布了同样的问题一个分钟后? – 2013-05-11 20:39:21

+0

我无法编辑标题,对不起,我很笨拙 – poppel 2013-05-11 21:18:46

回答

0

从理论上讲,你应该有什么样的工作,因为读操作是异步的。也许这是阻止执行的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); 
+0

thanx,我检查了一下,gif动画简短,然后停止,当加载开始 – poppel 2013-05-11 21:23:55

+0

我怀疑瓶颈是加载一个巨大的数据URL到IMG元件。尝试使用画布代替。 – bfavaretto 2013-05-11 22:01:03

+0

当我使用画布时,它也静止不动,但加载速度更快 – poppel 2013-05-11 22:27:22

0

加载的事件应该先挂钩。试试这个:

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';