Javascript如何运行(在前端执行)?

使用方式

HTML页面中的任意位置加上<script type=”module”></script>标签即可。

常见使用方式

1.直接在<script type=”module”></script>标签内写JS代码。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script type="module">
console.log('Hello World');
</script>
</body>

</html>

js1.png

2.直接引入文件:<script type=”module” src=”/static/js/index.js”></script>。

例如:
js2.png

1
2
3
4
5
6
<body>
<script type="module" src="/static/js/index.js"></script>
<script type="module">
console.log('Hello World');
</script>
</body>

js3.png

3.将所需的代码通过import关键字引入到当前作用域。

/static/js/index.js:

1
2
3
4
5
6
7
8
9
10
11
let name = "lzh";
let age = 18;

function print() {
console.log("My name is " + name);
}

export {
name,
print
}
1
2
3
4
5
6
7
8
9
<body>
<script type="module">
import { name, print } from "/static/js/index.js";
console.log(name);
print();
//这句话会报错,因为age没有export
//console.log(age);
</script>
</body>

js4.png

执行顺序

  • 类似于HTML与CSS,按从上到下的顺序执行;
  • 事件驱动执行(前端的事件,如点击,键盘输入等);

HTML,CSS和JavaScript之间的关系

  • CSS控制HTML
  • JavaScript控制HTML与CSS
  • 为了方便开发与维护,尽量按照上述顺序写代码。例如:不要在HTML中调用JavaScript中的函数。