Skip to content
On this page

引入 JS

三种常见导入

行内导入 JS(慎重:不安全)

html
<div onclick="alert('hello world')"></div>
1

内嵌式

html
<script>
	alert('hello world')
</script>
1
2
3

外链式

html
// 新建一个js文件
<script src="./js/demo.js"></script>

// or

<script src="./js/demo.js" type="text/javascript"></script>
1
2
3
4
5
6

script 元素

  • src
    • 没有这个属性。表示包含行内 js 代码
    • 有这个属性,用于指定加载的外部 js 文件
  • type
    • 在浏览器中,值始终为"text/javascript"
    • 如果加载或包含 ES 模块代码,值为"module"
  • nomodule
    • 兼容不支持 ES6 的浏览器:主要是 IE
  • async
  • defer
  • intergrity
  • Subresource Intergity
    • 浏览器在加载带有 intergrity 属性的<script><link>标签时,在下载完文件后,会先比较自己计算的散列值与 intergrity 属性的值,如果不相等,则返回网络错误

内嵌与外链不能同时操作

内嵌导入和外链导入不能合并在一起,如果当前是外链导入的,那么在 script 脚本块找那个编写的所有代码都不会被执行。

javascript
<script src="./js/demo.js">
  alert('hello world')
</script>
1
2
3

位置编写位置

我们一般性会把 css 放在 body 的上面,把 js 放在 body 末尾(约定速成的规范)

但是如果放在了标签前面那么将如何处理?

页面加载完所有资源之后执行操作

在 js 中

javascript
window.onload=function(){

}

1
2
3
4

在 jq 中

javascript
$(document).ready(function(){

})

window.addEventListener('load',function(){},false);

// ie8以下

window.attachEvent('onreadystatechange',function(){
})
1
2
3
4
5
6
7
8
9
10

沪ICP备20006251号-1