日期:2014-05-16 浏览次数:20412 次
六.Responsive Interfaces
?? There’s nothing more frustrating than clicking something on a web page and having nothing happen. This problem goes back to the origin of transactional web applications and resulted in the now-ubiquitous “please click only once” message that accompanies most form submissions. A user’s natural inclination is to repeat any action that doesn’t result in an obvious change, and so ensuring responsiveness in web applications is an important performance concern.
? Chapter 1 introduced the browser UI thread concept. As a recap, most browsers have a single process that is shared between JavaScript execution and user interface updates. Only one of these operations can be performed at a time, meaning that the user interface cannot respond to input while JavaScript code is executed and vice versa. The user interface effectively becomes “locked” when JavaScript is executing; managing how long your JavaScript takes to execute is important to the perceived performance of a web application.
<html> <head> <title>Browser UI Thread Example</title> </head> <body> <button onclick="handleClick()">Click Me</button> <script type="text/javascript"> function handleClick(){ var div = document.createElement("div"); div.innerHTML = "Clicked!"; document.body.appendChild(div); } </script > </body> </html>? ?When the button in this example is clicked, it triggers the UI thread to create and add two tasks to the queue. The first task is a UI update for the button, which needs to change appearance to indicate it was clicked, and the second is a JavaScript execution task containing the code for handleClick(), so that the only code being executed is this method and anything it calls. Assuming the UI thread is idle, the first task is retrieved and executed to update the button’s appearance, and then the JavaScript task is retrieved and executed. During the course of execution, handleClick() creates a new <div> element and appends it to the <body> element, effectively making another UI change. That means that during the JavaScript execution, a new UI update task is added to the queue such that the UI is updated once JavaScript execution is complete.