web前端笔记(4)-js引入(Web front end notes (4) – JS introduction)

JS两种引入方式

1.引用外部js文件

2.在页面中嵌入js

这是在页面使用js最简单的方式了,一般我在写个小测试的情况下会用这种方式。

把script元素写在</body>前面,script元素的内容就是js代码。像这样:

<script>
// 在这里写js
function test(){
alert('hello,world'); 
}
test();
</script>

script元素在HTML文件中的位置

如果把script元素放在head元素里,就像这样:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="xxx.js"></script>
</head>
<body>
<!--页面内容-->
</body>
</html>

这样做的话,待浏览器经过下载、解析、执行完js文件之后,才会呈现页面内容。如果一个页面需要很多个js文件,那么浏览器可能会出现很多问题,用户体验不好。

因此,正确的位置应是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>
<script>
    <--js内容-->
</script>
————————

JS is introduced in two ways

1. < strong > reference external JS files < / strong >

< strong > 2. Embed JS in the page < / strong >

This is the simplest way to use js on a page. I usually use this way when I write a small test.

Write the script element in & lt/ body> Previously, the content of the script element is JS code. like this:

<script>
// 在这里写js
function test(){
alert('hello,world'); 
}
test();
</script>

script元素在HTML文件中的位置

If you put the script element in the head element, it looks like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="xxx.js"></script>
</head>
<body>
<!--页面内容-->
</body>
</html>

In this way, the page content will not be presented until the browser has downloaded, parsed and executed the JS file. If a page needs many JS files, the browser may have many problems and poor user experience.

Therefore, the correct position should be:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>
<script>
    <--js内容-->
</script>