pco*_*ier 26 javascript jquery dom high-load
我要做的是在执行CPU密集型脚本之前更新一个简单的div来说"Processing ..."(运行需要3-12秒,没有AJAX)然后更新div来说"完成! " 完成后.
我所看到的是div永远不会更新"Processing ...".如果我在该命令后立即设置断点,则div文本会更新,所以我知道语法是正确的.IE9,FF6,Chrome13中的行为相同.
即使绕过jQuery并使用基本的原始Javascript,我也看到同样的问题.
你认为这会有一个简单的答案.但是,由于jQuery .html()和.text()没有回调挂钩,因此不是一个选项.它也没有动画,所以没有.queue可以操纵.
你可以使用下面我准备的示例代码来测试这个,它显示了具有5秒高CPU功能的jQuery和Javascript实现.代码很容易理解.单击按钮或链接时,您永远不会看到"正在处理..."
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript">
function addSecs(d, s) {return new Date(d.valueOf()+s*1000);}
function doRun() {
document.getElementById('msg').innerHTML = 'Processing JS...';
start = new Date();
end = addSecs(start,5);
do {start = new Date();} while (end-start > 0);
document.getElementById('msg').innerHTML = 'Finished JS';
}
$(function() {
$('button').click(function(){
$('div').text('Processing JQ...');
start = new Date();
end = addSecs(start,5);
do {start = new Date();} while (end-start > 0);
$('div').text('Finished JQ');
});
});
</script>
</head>
<body>
<div id="msg">Not Started</div>
<button>jQuery</button>
<a href="#" onclick="doRun()">javascript</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
use*_*654 18
将其设置为处理,然后执行setTimeout以防止cpu密集型任务运行,直到更新div为止.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script>
function addSecs(d, s) {return new Date(d.valueOf()+s*1000);}
function doRun() {
document.getElementById('msg').innerHTML = 'Processing JS...';
setTimeout(function(){
start = new Date();
end = addSecs(start,5);
do {start = new Date();} while (end-start > 0);
document.getElementById('msg').innerHTML = 'Finished Processing';
},10);
}
$(function() {
$('button').click(doRun);
});
</script>
</head>
<body>
<div id="msg">Not Started</div>
<button>jQuery</button>
<a href="#" onclick="doRun()">javascript</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你可以根据需要修改setTimeout延迟,对于较慢的机器/浏览器,它可能需要更大.
编辑:
您还可以使用警报或确认对话框来更新页面时间.
document.getElementById('msg').innerHTML = 'Processing JS...';
if ( confirm( "This task may take several seconds. Do you wish to continue?" ) ) {
// run code here
}
Run Code Online (Sandbox Code Playgroud)