current position:Home>JavaScript Ninja -- Chapter 2 Notes

JavaScript Ninja -- Chapter 2 Notes

2021-08-22 06:26:55 Mzs-Qsy

2、 The page building process at run time

2.1 Life cycle Overview

Typical client Web The life cycle of the application starts with the user entering a string in the browser address bar URL, Or start with a link


From the user's point of view , The browser builds the request to the server (2), The server processed the request (3) And form a system usually composed of HTML、CSS and JavaScript The response composed of code . When the browser accepts the response (4) when , Our client application begins its life cycle . Because of the client side Web Applications are graphical user interfaces (GUI) application , Its life cycle is similar to other GUI Application similarity ( For example, standard desktop applications or mobile applications ), The execution steps are as follows :

  1. Page building -- Create a user interface
  2. Event handling -- Into the loop (5) To wait for events (6) Happen , The event handler is called after occurrence

The life cycle of the application as the user closes the page (7) The end of . Now let's look at a simple example program :

Sample code :

<!DOCTYPE html>
  <title>Web app lifecycle</title>
    /* The corresponding is ul*/
    #first {
      color: green;

    #second {
      color: red;
<ul id="first"></ul>

  function addMessage(element, message) {
    // Add one li label 
    var messageElement = document.createElement('li'
    messageElement.textContent = message

  var first = document.getElementById('first')
  /* Call function , Pass in first*/
  addMessage(first, 'Page loading')

<ul id="second"></ul>

  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')


The execution result of the sample code in the browser


2.2 Page building phase

​ At present Web Before the application can be displayed or interacted , Its page must be based on the response obtained by the server ( Usually HTML、CSS and JavaScript Code ) To build . The goal of the page building phase is to create Web Applied UI, Its application mainly includes two steps :

1.  analysis HTML Code and build the document object model (DOM)
2.  perform JavaScript Code 

This step will be processed in the browser HTML Nodes are executed in the process , Step two will be in HTML Resolve to a special node -- Script node ( To include or refer to JavaScript The nodes of the code ) When the . In the page building phase , These two steps will be executed alternately several times , As shown in the figure below


​ The page building phase begins with browser acceptance HTML Code , This stage builds the page for the browser UI The basis of , By parsing the received HTML Code , Construct a HTML Elements , structure DOM. In this kind of right HTML In the form of structured representation , Every HTML The element is treated as a node , Until the first script element is encountered , Sample pages are being built DOM.

​ All nodes have only one parent node , for example ,head Node parent node is html node , meanwhile , A node can have any number of child nodes , for example html There are two children in the Department :head Nodes and body node . At the same time, the child node of an element is called brother to two .(head node body Node is brother node ) Even though DOM It's based on HTML To create , The two are closely linked , But it needs to be emphasized that , They are not the same . You can take HTML Think of the code as a browser page UI Build the initial DOM The blueprint of . In order to correctly build each DOM, The browser will also fix the problems it finds in the blueprint . As shown in the figure below


chart 2.5 Shows a simple error HTML Code example , On the page head Element incorrectly contains a paragraph Elements .head The general purpose of the element is to present the overall information of the page , For example, page title 、 Character encoding and external style scripts , Instead of defining page content like in this example


At present HTML The version is HTML5, Can pass See what features are available in the current release . If you need more readable documents MDN

​ In the construction phase of the page , Browsers will encounter special types of HTML Elements -- Script elements , This element is used to include JavaScript Code . Whenever the script element is parsed , The browser will stop from HTML structure DOM, And start execution JavaScript Code

2.2.1 perform JavaScript Code

​ All contained in script elements JavaScript The code is from the browser JavaScript The engine performs , for example Firefox Of Spidermonkey engine ,chrome and opera and V8 The engine and Edge Of Chakra engine , Because the main purpose of the code is to provide dynamic pages , Therefore, the browser provides a global object API yes JavaScript The engine can interact with it and change the content of the page

JavaScript Global object

​ Browser exposure to JavaScript The main global objects of the engine are window object , It represents a window that contains a page ,window Object is to get all other Global object Global variables ( It even contains user-defined objects ) and browser API Access to . overall situation window The most important attribute of an object is document, It represents the current page's DOM. By using this object ,JavaScript The code can change in any way DOM, This includes modifying or removing existing nodes , And creating and inserting new nodes

var first = document.getElementById("first")

Global is used in this example document Object through ID Choose an element , Then assign the element to the variable first, Then we can use it on this element JavaScript Code to do various operations on it , For example, change the text content , Modify properties , Dynamically create and add new child nodes , Shenzhen can be from DOM Remove the element

​ This book will describe a series of browser built-in objects and functions from beginning to end . But I'm sorry , All the features supported by browsers are beyond the scope of this book JavaScript The scope of the , adopt MDN You can check WebAPI The state of the interface

document Key value pairs for global objects




2.2.2 JavaScript Different types of code

We can roughly distinguish different types of JavaScript Code :

  • 1. Global code

  • 2. function code

Listing will help you understand the difference between the two types of code

detailed list

	function addMessage(element.message){
		var messageeElement = document.createElement('li')
		messageElement.textContent = message
        // Function code refers to the code contained in a function 

	var first = document.getElementById("first")
    addMessage(first,"page loading")
	// Global code refers to code that is outside the function code 

​ The main difference between the two types of code is their location : The code contained in a function is called function code , In all functions, unexpected code is called global code

​ The two codes are also different in execution ( Then you will see some other differences , Especially in the 5 In the chapter ). Global code by JavaScript The engine executes automatically in a direct manner , Whenever such code is encountered, it is executed line by line . for example , It's defined in addMessage The global code snippets in the function use built-in methods getElementById To get ID by first The elements of , Then call addMessage function , Whenever these codes are encountered, they will be executed one by one .

​ In turn, , If you want to execute function code , Must be called by other code : It can be all that code ( For example, due to the execution of global code addMessage function code , therefore addMessage Function must be called , It could be something else , It can also be called by the browser )

2.2.3 In the page build phase JavaScript Code

​ When the browser encounters a script node during the page construction phase , He will stop HTML and DOM The construction of , Turn to execution JavaScript Code , That is, execute the global contained in the script element JavaScript Code ( And the function code invoked in global code execution. ). Let's look at the sample code in listing

​ The following code shows the global JavaScript After the code is executed DOM The state of , Let's take a closer look at this implementation process , So we define one addMessage function

function addMessage(element,message){
	var messageElement = document.createElement('li')
	messageElement.textContent = message

Then through the global document On the object getElementById Methods from DOM Got an element on

var first = document.getElementById("first")

This code is followed by a pair of functions addMessage Call to

addMessage(first,"page loading")

This code creates a new li Elements , Then modify the text content , Finally, insert it DOM in


​ In this case ,JavaScript By creating a new element and inserting it DOM Node modifies the current DOM structure . Generally speaking ,JavaScript The code can be modified to any extent DOM structure , He can create new orders or remove existing ones DOM node , But it still can't do something , For example, select and modify nodes that have not been created , That's why script The reason why the element is placed at the bottom of the page , In this way , We don't have to worry about whether someone HTML Element already loaded DOM

​ 1. By analyzing variables messageElement Print discovery for ,li The tag itself is also an instance object , His prototype object points to HTMLElement, in other words DOM The element is also an instance object , Because he's __proto__ Points to its own prototype object HTMLelement



​ 2. Yes HTMLElement Print and find that it is also a function object ( Prototype object of variable )


once JavaScript The engine executed a script element JavaScript The last line of code , The browser exited JavaScript Execution mode , And continue to HTML Build for DOM node . in the meantime , If the browser encounters script elements again , So from HTML To DOM The build of is paused again ,JavaScript The operating environment starts executing the remaining JavaScript Code . We need to pay more attention to :JavaScript The application will remain in the global state at this time

<!DOCTYPE html>
	<title>Different types of JavaScript code – global and function code</title>
		#first {color: green;}
		#second {color: red;}
<ul id = "first"></ul>

	function addMessage(element, message) {
		var messageElement = document.createElement('li');	//#A
		messageElement.textContent = message;			          //#A
		element.appendChild(messageElement);			          //#A

	var first = document.getElementById('first');		      //#B
	addMessage(first, 'Page loading');				            //#B
<!--#A – function code is the code contained within a function
	#B – global code is the code outside functions -->
<ul id = "second"></ul>


2.3 Event handling

​ A client GUI application , In other words, this application will respond to different types of time , Such as mouse movement 、 Stand alone and keyboard pressing, etc . because , Performed during the page build phase JavaScript Code , In addition to affecting the global application status and modification DOM Outside , Event listeners are also registered . This kind of listener will be used when an event occurs , Executed by browser call , With these event handlers , Our applications have the ability to interact , Before we go into more detail about registering event handlers , Let's look at the overall idea of event handlers from beginning to end

2.3.1 Overview of event processors

​ The core idea of browser execution environment is based on : Only one code fragment can be executed at a time , The so-called single thread execution model . Imagine standing in line at the bank counter , Everyone has been in line waiting for call and processing , but JavaScript It opens a business counter whenever it's a customer's turn , Only one customer can be handled

  • Browser check event queue header
  • If the browser does not detect an event in the queue , Then continue to check
  • If the browser detects an event in the queue header , Then take out the event and execute the corresponding event handler . In the process , The remaining events wait patiently in the event queue

Because only one event can be processed at a time , We must pay special attention to the total time to deal with all events . Executing a processing function that takes a lot of time to execute will result in Web No response from application


​ Focus on the browser's mechanism in this process , The queue in which events are placed is outside the page construction phase and event processing phase . This process is important for determining when an event occurs

​ General manager Zhao , This architecture is currently Vue The most perfect and reliable enterprise level middle and back office solution in the ecology , Stable technology stack is used , Refine a typical business model , Built in excel Of

2.3.2 Register event handler

​ An event handler is a function that we want to execute when a particular event occurs , To achieve this goal , We told the browser that we were going to deal with that event , This process is called registering event handlers , On the client side Web Application ,

  • By assigning a function to a special attribute
  • By using the built-in addEventListener

Assign a function to window Object onload, In this way , The event handler will register with load Incident ( When DOM It's ready and fully built , Will trigger this event ).( If you're confused about the notation to the right of the assignment operator , Don't worry about , In the following chapters, we will be detailed )

2.3.3 Handling events

​ The main idea behind event handling is : When the event occurs , The browser invokes the event handling of the response , As mentioned earlier , Due to the single thread execution model , So only one event can be processed at a time . Any subsequent events can only be processed after the current event handler has completely completed execution

2.4 Summary

  • Browser accepted HTML Code used to create DOM The blueprint of , It's the client side Web Internal presentation stage of application structure
  • We use JavaScript Code to dynamically modify DOM In order to give Web Applications bring dynamic behavior
  • client Web The implementation of the application is divided into two stages
    • The page build phase is for creating DOM Of , And the whole picture JavaScript Code encountered script Node . During this execution ,JavaScript The code can change the current to any degree DOM, You can also register event handlers -- An event handler is a function , When a particular event ( for example , One mouse or keyboard press ) It will be executed after it occurs . Registering event handlers is easy : Use the built-in addEventListener Method
    • Event handling -- At the same time , Only one of several different events can be processed , The order in which events are generated when processing sequences . The event processing phase relies heavily on event queues , All events are stored in the event queue in the order they appear . The event loop checks the header of the event queue , If an event is detected , Then the corresponding event handler will be called

2.5 practice

1. client Web What are the two life cycle phases of an application ?

  • Page building phase

    • Two steps :1. analysis html Code and build the document object model (DOM) 2. perform JavaScript Code
      All contained in script elements JavaScript The code is generated by the browser JavaScript The engine performs , Because the main purpose of the code is to provide dynamic pages , Therefore, the browser passes through global objects window Provides API and window The most important attribute document, send JavaScript The engine can interact with the page and change the page content .
      When page building encounters JavaScript The code will stop html To dom The construction of , And then it's done JavaScript The last line of code , The browser exits JavaScript Execution mode , And continue the rest html To build a dom node . When the script element is encountered again , Because of the overall situation window Objects exist throughout the life cycle of the page , All the information is stored on him JavaScript Variable . So as long as there's still unfinished business html Elements and unfinished JavaScript Code , Then the two steps will always be performed alternately .
  • Event handling stage

    • The core idea of browser execution environment is based on : Only one code fragment can be executed at a time , The so-called single thread execution model . So browsers use queues to track events that have occurred but have not yet been processed .

      Our handling of events is asynchronous , Such as

      Browser Events , For example, the page cannot be loaded after loading
      Internet Events , For example, a response from a server (ajax Events and server events )
      User events , For example, mouse click , Mouse movement, etc
      Timer events , When timeout Time expired or another event interval triggered

2. Instead of assigning an event handler to an attribute of a particular element , Use addEventListener What are the advantages of using the method to register event handlers ?

  • By assigning a function to a special attribute
  • By using the built-in addEventListener
window.onload = function (){}

Assigning functions to special properties is a simple and direct way to register event handlers . however , We do not recommend that you use this method to register event handlers , This is because of the disadvantages of this approach , Only one event handler can be registered for an event , That is to say , If you are not careful, the last event handler will be rewritten , Another alternative is to use addEvenetListener Method allows us to register as many events as possible , As long as we need . The following list uses the list 2.3 Example in

// by mousemove Event registration processor 
	var second = document.getElementById("second")
// by click Event registration processor 
	var second = document.getElementById("second")


3.JavaScript How many events can the engine handle at the same time ?

javascript The engine can only process one event at a time

4. In what order are the events in the event queue processed ?

The processing order is the order in which events are generated , The event processing phase relies heavily on event queues , All events are stored in the event queue in the order they appear . The event loop checks the queue header of the event queue , If an event is detected , Then the corresponding event handler will be called

copyright notice
author[Mzs-Qsy],Please bring the original link to reprint, thank you.

Random recommended