How to enable javascript in the browser and how to run js in the browser

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.

  1. Parsing code: HTML code is parsed into DOM, CSS code is parsed into CSSOM (CSS Object Model).
  2. Object synthesis: combine DOM and CSSOM into a render tree.
  3. Layout: Calculate the layout of the render tree.
  4. 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 or fixed 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:

  1. Read the code, perform lexical analysis, and decompose the code into tokens.
  2. Perform grammatical analysis (parsing) of word elements and organize the code into a “syntax tree”.
  3. Use a “translator” to convert the code into bytecode.
  4. 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.

  1. Create an XMLHttpRequest instance
  2. Make an HTTP request
  3. Receive data returned by the server
  4. 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 defaults 80 and 433, 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 (#)
  • 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.

Both the element and the

element deploy this interface. This means that their DOM node objects can use URL’s instance properties and methods.

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 (

) are used to collect data submitted by users and send it to the server. For example, if a user submits a username and password for the server to verify, they must go through a form. The form provides a variety of controls for developers to use. For specific control types and usage, please refer to the HTML language tutorial.

19. IndexedDB is a local database provided by the browser, which can be created and operated by web scripts. IndexedDB allows storage of large amounts of data, provides a search interface, and can also create indexes. These are things that LocalStorage does not have. In terms of database type, IndexedDB is not a relational database (does not support SQL query statements) and is closer to a NoSQL database.

IndexedDB has the following characteristics.

(1) Key-value pair storage. IndexedDB uses an object store internally to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is stored in the form of “key-value pairs”. Each data record has a corresponding primary key. The primary key is unique and cannot be repeated, otherwise an error will be thrown.

(2) Asynchronous. IndexedDB does not lock the browser during operation, and users can still perform other operations. This is in contrast to LocalStorage, which operates synchronously. Asynchronous design is to prevent the reading and writing of large amounts of data from slowing down the performance of web pages.

(3) Support transactions. IndexedDB supports transactions, which means that if one step in a series of operation steps fails, the entire transaction will be cancelled, and the database will be rolled back to the state before the transaction. There is no need to rewrite only part of the data. .

(4) Homology restriction. IndexedDB is subject to same-origin restrictions, and each database corresponds to the domain name where it was created. Web pages can only access databases under their own domain names, but not cross-domain databases.

(5) Large storage space. The storage space of IndexedDB is much larger than LocalStorage, generally no less than 250MB, and there is no upper limit.

(6) Support binary storage. IndexedDB can store not only strings, but also binary data (ArrayBuffer objects and Blob objects).

20. The role of Web Worker is to create a multi-threaded environment for JavaScript, allowing the main thread to create Worker threads and assign some tasks to the latter for execution.

Once the Worker thread is successfully created, it will always run and will not be interrupted by activities on the main thread (such as the user clicking a button or submitting a form). This is conducive to responding to the main thread’s communication at any time. However, this also causes Worker to consume more resources and should not be overused, and should be shut down once used.

Web Worker has the following points to note when using it.

(1)Homology restriction

The script file assigned to the Worker thread must have the same origin as the script file of the main thread.

(2)DOM restrictions

The global object where the Worker thread is located is different from the main thread. It cannot read the DOM object of the web page where the main thread is located, and cannot use document, window, parentThese objects. However, Worker threads can use navigator objects and location objects.

(3)Global object restrictions

The global object of Worker WorkerGlobalScope is different from the global object of web page Window, and many interfaces are not available. For example, in theory, the Worker thread cannot use console.log, because the standard does not mention that the global object of Worker has the console interface, and only defines Navigatorinterface and Locationinterface. However, browsers actually support the use of console.log for Worker threads, and the safest approach is not to use this method.

(4)Correspondence

The Worker thread and the main thread are not in the same context, they cannot communicate directly and must be completed through messages.

(5)Script restrictions

The Worker thread cannot execute the alert() method and the confirm() method, but it can use the XMLHttpRequest object to make AJAX requests.

(6)File restrictions

The Worker thread cannot read local files, that is, it cannot open the local file system (file://). The script it loads must come from the network.