High Performance JavaScript by Nicholas C. Zakas

High Performance JavaScript by Nicholas C. Zakas

Author:Nicholas C. Zakas
Language: eng
Format: mobi, epub, pdf
Tags: COMPUTERS / Programming Languages / JavaScript
Publisher: Yahoo Press
Published: 2010-03-11T05:00:00+00:00


The Browser UI Thread

The process shared by JavaScript and user interface updates is frequently referred to as the browser UI thread (though the term “thread” is not necessarily accurate for all browsers). The UI thread works on a simple queuing system where tasks are kept until the process is idle. Once idle, the next task in the queue is retrieved and executed. These tasks are either JavaScript code to execute or UI updates to perform, which include redraws and reflows (discussed in Chapter 3). Perhaps the most interesting part of this process is that each input may result in one or more tasks being added to the queue.

Consider a simple interface where a button click results in a message being displayed on the screen:

<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. See Figure 6-1.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.