This article mainly introduces where to set the browser’s javascript, which has certain reference value. Friends in need can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to understand it together.
1. The core of the browser is two parts: the rendering engine and the JavaScript interpreter (also known as the JavaScript engine).
The main function of the rendering engine is to render the web page code into a flat document GPT that the user can visually perceive.
Different browsers have different rendering engines.
The rendering engine processes web pages, usually in four stages.
- Parsing code: HTML code is parsed into DOM, CSS code is parsed into CSSOM (CSS Object Model).
- Object synthesis: combine DOM and CSSOM into a render tree.
- Layout: Calculate the layout of the render tree.
- Draw: Draw the render tree to the screen.
The above four steps are not strictly executed in order. Often the second and third steps have already started before the first step is completed. Therefore, you will see this situation: the HTML code of the web page has not been downloaded, but the browser has already displayed the content.
2. Rendering engine, small skills for optimizing redrawing and reflowing:
- Read DOM or write DOM, try to write them together, don’t mix them. Don’t read a DOM node, then immediately write, then read a DOM node again.
- Cache DOM information.
- Instead of changing styles one by one, use CSS classes to change styles all at once.
- Use
documentFragment
to manipulate DOM - Animation uses
absolute
positioning orfixed
positioning, which can reduce the impact on other elements. - Show hidden elements only when necessary.
- Use
window.requestAnimationFrame()
because it defers code execution until the next reflow, rather than requiring the page to be reflowed immediately. - Use virtual DOM (virtual DOM) library.
3. Browser JavaScript engine
Main function: Read the JavaScript code in the web page, process it and run it.
JavaScript is an interpreted language, that is, it does not require compilation and is run in real time by an interpreter. Advantages: It is more convenient to run and modify, and it can be reinterpreted by refreshing the page; Disadvantages: The interpreter must be called every time it is run, which requires a large system overhead and runs slower than compiled languages.
In order to improve the running speed, current browsers compile JavaScript to a certain extent and generate intermediate code similar to bytecode to improve the running speed.
In the early days, the browser’s internal processing of JavaScript was as follows:
- Read the code, perform lexical analysis, and decompose the code into tokens.
- Perform grammatical analysis (parsing) of word elements and organize the code into a “syntax tree”.
- Use a “translator” to convert the code into bytecode.
- Use a “bytecode interpreter” to convert bytecode into machine code.
Line-by-line interpretation to convert bytecode into machine code is very inefficient. In order to improve the running speed, modern browsers use “Just In Time compiler” (JIT) instead, that is, the bytecode is only compiled at runtime, whichever line is used is compiled, and the compilation results are cached ( inline cache). Usually, only a small part of the code in a program is frequently used. With cached compilation results, the running speed of the entire program will be significantly improved.
The bytecode cannot be run directly, but runs on a virtual machine (Virtual Machine). The virtual machine is also generally called a JavaScript engine.
Not all JavaScript virtual machines have bytecode when running. Some JavaScript virtual machines are based on source code. That is, whenever possible, the source code is directly compiled into machine code and run through a JIT (just in time) compiler, omitting the bytecode. step. This is different from other languages that use virtual machines (such as Java). The purpose of this is to optimize the code and improve performance as much as possible. The following are some of the most common JavaScript virtual machines currently available:
- Chakra (Microsoft Internet Explorer)
- Nitro/JavaScript Core (Safari)
- Carakan (Opera)
- SpiderMonkey (Firefox)
- V8 (Chrome, Chromium)
4. The window object refers to the current browser window and is also the top-level object of the current page, that is, the highest-level object.
If a variable is not declared, it defaults to a property of the top-level object.
window.open can open a new window.
5. window.requestAnimationFrame() postpones the execution of a certain function until the next reflow of the browser. The next redraw will not occur until the execution is completed.
If a function will change the layout of the web page, it is usually executed inside window.requestAnimationFrame()
, which saves energy and smoothes the web page effect.
window.requestIdleCallback() defers execution until system resources are idle.
6. The window.navigator
property points to a Navigator object that contains browser and system information. The script uses this attribute to learn about the user’s environment information.
7.Cookie is a small piece of text information saved by the server in the browser. The general size cannot exceed 4KB. Every time the browser makes a request to the server, it automatically attaches this information.
Cookies primarily store state information, here are some of their main uses.
- Session management: Save login, shopping cart and other information that needs to be recorded.
- Personalized information: Save user preferences, such as web page font size, background color, etc.
- Track users: record and analyze user behavior.
Cookies are not an ideal client-side storage mechanism. Its capacity is small (4KB), lacks data operation interface, and will affect performance. Client storage should use the Web storage API and IndexedDB. Only information that needs to be known to the server for each request should be placed in cookies.
Each cookie has the following metadata.
- Cookie name
- Cookie value (the real data is written here)
- Expiration time (it will become invalid after this time)
- Domain name (default is current domain name)
- Effective path (defaults to the current URL)
8. AJAX (Asynchronous JavaScript and XML): AJAX issues an HTTP request through the native XMLHttpRequest
object, and then processes the data returned by the server. Now, the server returns data in JSON format, and the XML format is obsolete, but the name AJAX has become a common noun and the literal meaning has disappeared.
AJAX includes the following steps.
- Create an XMLHttpRequest instance
- Make an HTTP request
- Receive data returned by the server
- Update web page data
9. Same origin: three are the same; the same protocol, the same domain name, and the same port.
Cookies set by web page A cannot be opened by web page B unless the two web pages have the same origin. The same origin is to ensure the security of user information and prevent malicious websites from stealing data.
If they are not of the same origin, there are three restrictions:
(1) Cookie, LocalStorage and IndexedDB of non-original web pages cannot be read.
(2) The DOM of non-homogeneous web pages cannot be accessed.
(3) An AJAX request cannot be sent to a non-original address (it can be sent, but the browser will refuse to accept the response).
9. CORS is a W3C standard, whose full name is “Cross-origin resource sharing”. It allows the browser to issue XMLHttpRequest
requests to cross-domain servers, thus overcoming the limitation that AJAX can only be used from the same origin.
10. The Storage interface is used by scripts to save data in the browser. Two objects deploy this interface: window.sessionStorage
and window.localStorage
.
- sessionStorage: The saved data is used for a browser session. When the session ends (usually the window is closed), the data is cleared;
- localStorage: The saved data exists for a long time. The next time you visit the website, the web page can directly read the previous data.
The two stroages are identical in other aspects except for the different storage periods. They are both in key-value format.
storage supports event monitoring of data changes.
11. The window.history
property points to the History object, which represents the browsing history of the current window.
The History object stores the URLs of all pages visited by the current window.
window.history.length //Represents how many URLs the current window has visited
history.back() or history.go(-1) //Return to the previous page
History.state: The state value at the top of the History stack.
History.forward(): Move to the next URL, equivalent to the browser’s forward button. This method has no effect on the last visited URL.
History.go()
: accepts an integer as a parameter, moves to the URL specified by the parameter based on the current URL, for example, go(1)
is equivalent to forward ()
, go(-1)
is equivalent to back()
. If the parameter exceeds the actual URL range, this method has no effect; if no parameter is specified, the default parameter is 0
, which is equivalent to refreshing the current page.
Note that when moving to a previously visited page, the page is usually loaded from the browser cache rather than re-asking the server to send a new web page.
12. The Location
object is a native object provided by the browser, providing URL-related information and operation methods. This object can be obtained through the window.location
and document.location
properties.
The Location
object provides the following properties.
Location.href
: The entire URL.Location.protocol
: The protocol of the current URL, including colon (:
).Location.host
: Host. If the port is not the protocol defaults80
and433
, a colon (:
) and the port are also included.Location.hostname
: Host name, excluding port.Location.port
: Port number.Location.pathname
: The path part of the URL, starting from the root path/
.Location.search
: Query string part, starting with question mark?
.Location.hash
: Fragment string part, starting from#
.Location.username
: The user name in front of the domain name.Location.password
: The password in front of the domain name.Location.origin
: The protocol, hostname and port of the URL.
13. Write a new URL address into Location.href, and the browser will immediately jump to this new address.
// Jump to new URL document.location.href = 'http://www.example.com';
This feature is often used to allow web pages to automatically scroll to a new anchor point.
document.location.href = '#top'; // Equivalent to document.location.hash = '#top';
Directly rewriting location
is equivalent to writing the href
attribute.
document.location = 'http://www.example.com'; // Equivalent to document.location.href = 'http://www.example.com';
In addition, the Location.href
attribute is the only attribute that browsers allow cross-domain writing, that is, a non-same source window can overwrite the Location of another window (such as a child window and a parent window). href
attribute, causing the latter URL to jump. No other attributes of Location
are allowed to be written across domains.
Other methods:
Location.assign(): jump to new URL
Location.replace(): Jump to the new URL and replace the current URL in History
Location.reload(): Refresh
14: URL encoding and decoding
1) The URL of a web page can only contain legal characters. Legal characters include 2 categories:
- URL metacharacters
- Semicolon (
;
), comma (,
), slash (/
), question mark (?
), Colon (:
), at (@
),& amp;
, equal sign (=
), plus sign (+
), dollar sign ($
), pound sign (#
)
- Semicolon (
- Semantic characters
a-z
,A-Z
,0-9
, hyphen (-
), underline (_
code>), dot (.
), exclamation mark (!
), tilde (~
), asterisk (*
code>), single quotes ('
), parentheses (()
)
In addition to the above characters, other characters appearing in the URL must be escaped. The rule is to convert each character into a percent sign (%
) plus two uppercase characters according to the default encoding of the operating system. Hexadecimal letters.
2) JavaScript provides four URL encoding/decoding methods.
encodeURI()
- Used to transcode the entire URL. Its parameter is a string representing the entire URL. It will escape characters other than metacharacters and semantic characters.
encodeURIComponent()
- The component used to transcode a URL. All characters except semantic characters will be transcoded, i.e. metacharacters will also be transcoded. Therefore, it cannot be used to transcode the entire URL. It accepts one parameter, which is a fragment of the URL.
decodeURI()
decodeURIComponent()
15. The URL object is a native object of the browser and can be used to construct, parse and decode URLs. Generally, this object can be obtained through window.URL
.
var a = document.createElement('a'); a.href = 'http://example.com/?foo=1'; a.hostname // "example.com" a.search // "?foo=1"
In the above code, a
is the DOM node object of the element. You can use URL instance properties on this object, such as
hostname
and search.
16. The Blob object represents the data content of a binary file. For example, the content of an image file can be read and written through the Blob object. It is usually used to read and write files, and its name is the abbreviation of Binary Large Object. The difference between it and ArrayBuffer is that it is used to operate on binary files, while ArrayBuffer is used to operate on memory.
17.File object represents a file and is used to read and write file information. It inherits the Blob object, or is a special Blob object, which can be used in all situations where a Blob object can be used.
18. Forms (