Home > Web Front-end > JS Tutorial > body text

There are several ways to add javascript to a web page

醉折花枝作酒筹
Release: 2023-01-07 11:43:43
Original
8081 people have browsed it

There are two ways to add js to a web page, namely: 1. Direct method, the syntax format is "<script>js code</script>"; 2. Reference method, the syntax format is "< script src="js address" type="text/javascript">".

There are several ways to add javascript to a web page

1. Direct method

This is the most commonly used method. Most web pages containing Javascript use this method, such as:

<script type="application/javascript">
  <!--
  document.write("这是Javascript!采用直接插入的方法!");
  //-Javascript结束-->
  </script>
Copy after login

In this example, we can see a new tag: <script>...</script>, and

or .. ... anywhere.

There is also a more advanced version of the embedded script, which uses the CDATA syntax in HTML (Character Data, which treats all the text in CDATA as plain text, unless it encounters the end of CDATA)

<script language="javascript" type="text/javascript"><!--//--><!CDATA[[//><!--
  //javascript代码
  //--><!]]></script>
Copy after login

2. Reference method

If there is already a Javascript source file (usually with js extension), you can use this reference method to improve the utilization of the program code. The basic format is as follows:

<script src=“url” type="text/javascript"></script>
Copy after login

The Url is the address of the program file. Likewise, such statements can be placed in the head or any part of the body of an HTML document. If you want to achieve the effect of the example in the "Direct Insertion Method", you can first create a Javascript source code file "Script.js" with the following content:

document.write("这是Javascript!采用直接插入的方法!");
Copy after login

In the web page, you can call the program like this: < script src="Script.js" type="text/javascript"> .

You can also specify the javascript version when importing the file, for example:

Note: Any content in the script tag that specifies the src attribute will be ignored.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of There are several ways to add javascript to a web page. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template