加载js文件后可以立马执行里面的函数么

JavaScript012

加载js文件后可以立马执行里面的函数么,第1张

js中是有立即执行函数的,比如说js文件中有一个函数为:

function sayHello(){

console.log('Hello World!')

}

如果你想在js文件加载后,立即执行sayHello()函数,那么可以在js中加入

sayHello()的调用即可。

加上

defer

等于在页面完全在入后再执行,相当于

window.onload

,但应用上比

window.onload

更灵活

<!DOCTYPE

html

PUBLIC

"-//W3C//DTD

XHTML

1.0

Transitional//EN"

"

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html

xmlns="

http://www.w3.org/1999/xhtml">

<head>

<meta

http-equiv="Content-Type"

content="text/html

charset=utf-8"

/>

<title>无标题文档</title>

</head>

<body>

<script

defer="defer">

alert("页面加载完我才执行的")

</script>

先看到这段话

然后再执行上面的

JS

如果去掉上面的

defer="defer"

那么会先执行JS

在看到这段话

</body>

</html>