Monday, 26 of June of 2017

JavaScript and the Browser UI

High Performance JavaScript by Nicholas Zakas covers some interesting JavaScript issues I didn’t know. Typically, browsers have a single thread that is shared between the page’s JavaScript code and user interface updates. The also share a single queue of tasks for the thread to run. When JavaScript code is running, no UI updates can occur. They are blocked until the JavaScript code ends, freeing the thread. When the JavaScript code updates a DOM element no visible change is immediately made. Instead a new task is queued on the shared queue.

New browsers (Firefox 3.5) support “Web Workers”. Each new worker is given a new thread that is initialized by code loaded from the specified JavaScript file (e.g., new Worker(“foo.js”)). Worker threads can not update the UI; they don’t have access to the DOM and a bunch of other global variables. However they can send messages (with serializable objects) back and forth to code running in the shared UI thread. In the UI thread you could use a timer to periodically check for new messages and use their contents to modify the DOM.