I'm using eval() in javascript to evaluate a significant amount of js code (not just json, but 开发者_如何学Gofunction calls too). The browser freezes during the call, i.e. the user cannot scroll the browser or click anything. Is there any way around this freezing problem?
In most browsers, JavaScript runs on the UI thread, so it blocks the UI as you describe. The best way to un-block the UI is to break up the JS into smaller parts, and string them together with setTimeout (which gives control of the thread back to the browser for UI rendering)
You may also try executing the code by injecting a new script tag into the page:
function executeCode(code) {
var element = document.createElement('script');
element.type = 'text/javascript';
try {
element.appendChild(document.createTextNode(code));
document.body.appendChild(element);
}
catch (e) {
element.text = code;
document.body.appendChild(element);
}
}
var code = 'alert("hello world");';
executeCode(code);
You have to break up your function into smaller parts. I recommend combining them with setTimeout
.
In modern browsers there are web workers that can compute data in the background.
精彩评论