我正在尝试实时更新状态页面。
我正在使用 Ajax 来更新页面。更新设置为每 3 秒更新一次。但每当调用更新时,浏览器都会卡住至少一两秒。
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
如果有人能给我一些改进的建议。为了减少延迟或让它消失。
2)我一直在考虑使用JQuery。我应该采取行动吗?优点和缺点?另外,与 JavaScript 相比,JQuery 的性能如何?
最佳答案
您让 AJAX 请求同步运行 - 您永远不需要这样做,因为这首先会阻止它成为 AJAX,因为 A 代表异步。
将 xmlhttp.open
调用的第三个参数更改为 true
(或者直接将其省略,因为这是默认值)。
关于javascript - Ajax - 更新内容时浏览器滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830042/