Home>Article>Web Front-end> Summary of methods for embedding JS in HTML documents
This time I will bring you a summary of theHTML documentmethods of embedding JS, and what are theprecautionsfor embedding JS in HTML documents. The following is a practical case, let’s take a look.
Embedding JavaScript in HTML
There are 4 ways to embed client-side JavaScript code in HTML documents:
1 .Inline, placed between the tags (less);
2. Placed in an external file specified by the src attribute of the tags will be ignored.
When you include a script in a page using the src attribute, you give the script full control over the Web page.
3——Event handler in HTML
When the HTML file where the script is located is loaded into the browser, the JavaScript code in this script will only be executed once . JavaScript code can register event handlers by assigning functions to properties of the Element object. This Element object represents an HTML element in the document.
For example:
Copy codeThe code is as follows:
The attributes of the event handler defined in HTML can contain any JavaScript statements, separated by commas. These statements form the body of a function, which then becomes the value of the corresponding event handler property.
4 - JavaScript in the URL
Following the URL with a javascript: protocol qualifier is another way to embed JavaScript code into the client. This special protocol type specifies that the URL content is an arbitrary string, which is JavaScript code that will be run by the JavaScript interpreter. It is treated as a separate line of code, which means statements must be separated by semicolons and comments must be replaced by /**/ comments. The resource recognized by javascript:URL is the return value of the executed code converted into a string. If the code returns undefined, then the resource has no content.
javascript: The URL can be anywhere a regular URL can be used: such as the href attribute of thetag, the action attribute of