2.1 Lifecycle Overview

The life cycle of a typical client-side Web application begins when a user enters a string of urls into the browser address bar, or clicks a link. For example, we visit Baidu website. First, we entered the URL, www.baidu.com, as shown in Figure 2.1

The client-side Web application cycle starts with the user specifying a Web site address (or clicking a link) and consists of two steps: page building and event handling 1. Page building – creating the user interface; 2. Event processing – Enter a loop (no. 5) to wait for an event (No. 6) to occur and invoke the event handler.

2.2 Page Construction phase

Before a Web application can be displayed or interacted with, its pages must be built from the responses (usually HTML, CSS, and JavaScript code) that the server gets. The goal of the page construction phase is to build the UI of the Web application, which consists of two steps:

1. Parsing HTML code and building a document Object Model (DOM);

2. Execute JavaScript code.

Step 1 is executed while the browser is processing the HTML node, and Step 2 is executed when the HTML is parsed to a special script node (containing or referencing script nodes), alternating the two steps several times

HTML parsing and DOM building

The aspect construction phase begins when the browser receives THE HTML code and forms the basis for the browser to build the page UI. Build the DOM by parsing the RECEIVED HTML code, building each HTML element. In this structured representation of HTML, each HTML element is treated as a node.

Although the DOM is created from HTML and the two are closely related, it is important to emphasize that they are not the same. You can think of the HTML code as the blueprint for building the initial DOM of the browser page UI. To build each DOM correctly, the browser also fixes the problems it finds in the blueprint.

Note: If the page contains a Paragraph element in the head element by mistake. The general purpose of the head element is to display general information about the page, such as the page title, character encoding, and external style scripts, rather than to define the content of the page, as in this example. The browser silently fixes the error, puts the paragraph element in the body element where the page content should be, and constructs the correct DOM

2.2.2 Executing JavaScript Code

All JavaScript code contained in script elements is executed by the browser’s JavaScript engine, for example, the Spidermonkey engine for Firefox, the Chrome and Opera engines and the V8 engine for Edge (IE’s) Chakra engine. Since the main purpose of the code is to serve dynamic pages, the browser provides an API through the global object that the JavaScript engine can interact with and change the page content.

Execute JavaScript code during the page construction phase

When the browser encounters a script node during the page build phase, it stops the HTML-to-DOM build and starts executing JavaScript code instead, that is, executing the global JavaScript code contained within the script element (and the function code called by the global code execution).

Figure 2.2 shows the state of the DOM after the global JavaScript code has been executed. We start with an addMessage function

function addMessage (element,message){
        var messageElement = document.createElement("li")
        messageElement.textContent = message
        element.appendChild(messageElement)
     }
     var first = document.getElementById("first")
     addMessage(first,"page loading")

     document.body.addEventListener("mousemove",function (){
         var second = document.getElementById("second")
         addMessage(second,"event: mousemove")
     })
     document.body.addEventListener("click",function (){
         var second = document.getElementById("second")
         addMessage(second,"event: click")
     })
Copy the code

In this example, JavaScript modifies the current DOM structure by creating a new element and inserting it into the DOM node. In general, JavaScript code can modify the DOM structure in any way: it can create new orders or remove existing DOM nodes. But it still can’t do things like select and modify nodes that haven’t been created yet. This is why script elements are placed at the bottom of the page. This way, we don’t have to worry about whether an HTML element is already loaded as a DOM.

Once the JavaScript engine executes the last line of JavaScript code in the script element, the browser exits JavaScript execution mode and builds the rest of the HTML as DOM nodes. During this time, if the browser encounters a script element again, the HTML to DOM build is paused again, and the JavaScript runtime environment starts executing the rest of the JavaScript code. It is important to note that the JavaScript application remains global at this point. All global variables created by a user during the execution of a JavaScript code are normally accessed by JavaScript code in other script elements. The reason for this is that the global Window object exists for the lifetime of the page and stores all JavaScript variables on it. The next two steps alternate as long as there are unprocessed HTML elements and unexecuted JavaScript code.

1. Build HTML as DOM.

2. Execute JavaScript code.

Finally, when the browser has processed all the HTML elements, the page construction phase is over. The browser then moves on to the second part of the application life cycle: event handling.

2.3 Event Handling

A client-side Web application is a GUI application, which means it responds to different types of events, such as mouse movements, clicks, and keyboard presses. Therefore, JavaScript code executed during the page construction phase, in addition to affecting the global application state and modifying the DOM, registers event listeners (or handlers). This type of listener is executed by a browser call when an event occurs. With these event handlers, our applications have the ability to interact. Before diving into the details of registering event handlers, let’s walk through the general idea of event handlers

2.3.1 Event Handler Overview

The core idea behind the browser execution environment is that only one piece of code can be executed at a time, the so-called single-threaded execution model.

All generated events (whether user-generated, such as mouse movements or keyboard presses, or server-generated, such as Ajax events) are placed in the same event queue in the order in which they are detected by the browser. As shown in the middle of Figure 2.3, the process of event processing can be described as a simple flow chart.

● Browser checks the event queue header;

● If the browser does not detect an event in the queue, continue checking;

● If the browser detects an event in the queue header, it fetches the event and executes the appropriate event handler (if present).

In this process, the remaining events wait patiently in the event queue until it is their turn to be processed. Since only one event can be processed at a time, we have to pay extra attention to the total time it takes to process all events. Executing event handlers that take a lot of time to execute can make your Web application unresponsive!

2.3.2 Registering event handlers

Event handlers are the functions we want to execute when a particular event occurs. To achieve this, we must tell the browser which event we want to process. This process is called registering event handlers. In a client-side Web application, there are two ways to register events.

● By assigning a function to a special attribute;

Document.body.onclick = function (){}

● By using the built-in addEventListener method.

Note: Assigning functions to special attributes is a simple and straightforward way to register event handlers. However, it is not recommended that you register event handlers in this way because of the disadvantage of registering only one event handler for an event. That is, you can accidentally overwrite the last event handler. Fortunately, there is an alternative: the addEventListener method lets us register as many events as we need

2.3.3 Handling Events

The main idea behind event handling is that when an event occurs, the browser invokes the corresponding event handler. As mentioned earlier, due to the single-threaded execution model, only one event can be processed at a time. Any subsequent events can only be processed after the current event handler has completed execution!

In the event processing phase, the event loop checks the queue, finds a mouse movement event in front of the queue, and executes the corresponding event handler number 2. When the mouse movement event handler completes processing, it is the turn of the click event waiting in the queue. When the last line of the mouse move event handler function has been executed, the JavaScript engine exits the event handler function, the mouse move event completes the sequence number 3, and the event loop checks the queue again. This time, at the front of the queue, the event loop finds the mouse click event and processes it. Once the click handler completes and there are no new events in the queue, the event loop continues to loop, waiting to process new incoming events. This loop continues until the user closes the Web application.

2.4 summary

● The HTML code received by the browser serves as a blueprint for creating the DOM, which is the internal presentation stage of the client’s Web application structure.

● We use JavaScript code to dynamically modify the DOM to bring dynamic behavior to Web applications.

● The execution of the client Web application is divided into two phases. – Page build code is used to create the DOM, while global JavaScript code is executed when aScript node is encountered.

– During this execution, JavaScript code can alter the current DOM to any degree, and also register event handlers — functions that are executed when a particular event (for example, a mouse click or keyboard press) occurs. Registering event handlers is easy: use the built-in addEventListener method.

– Event processing – Only one of several different events can be processed at a time, in the order in which the event was generated. The event processing phase relies heavily on the event queue, where all events are stored in the order in which they appear. The event loop checks the header of the practice queue, and if an event is detected, the corresponding event handler is called.