How is JavaScript code introduced into HTML?

A JavaScript program cannot run on its own, it needs to be embedded in HTML before the browser can execute the JavaScript code. pass

<!DOCTYPE html>
 <html>
 <head>
   <meta charset="UTF-8">
   <title>JavaScript 基础 - 引入方式</title>
 </head>
 <body>
   <!-- 内联形式:通过 script 标签包裹 JavaScript 代码 -->
   <script>
     alert('嗨,欢迎来传智播学习前端技术!')
   </script>
 </body>
 </html>

2. External form

Generally, JavaScript code is written in a separate file ending with .js, and then passed

// demo.js
document.write('嗨,欢迎来传智播学习前端技术!')
<!DOCTYPE html>
 <html>
 <head>
   <meta charset="UTF-8">
   <title>JavaScript 基础 - 引入方式</title>
 </head>
 <body>
   <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
   <script src="demo.js"></script>
 </body>
 </html>

Note: If the script tag imports a .js file using the src attribute, the tag's code will be ignored! ! ! As shown in the following code:

<!DOCTYPE html>
 <html>
 <head>
   <meta charset="UTF-8">
   <title>JavaScript 基础 - 引入方式</title>
 </head>
 <body>
   <!-- 外部形式:通过 script 的 src 属性引入独立的 .js 文件 -->
   <script src="demo.js">
     // 此处的代码会被忽略掉!!!!
       alert(666);  
   </script>
 </body>
 </html>

Guess you like

Origin blog.csdn.net/cz_00001/article/details/131291725