码迷,mamicode.com
首页 > 其他好文 > 详细

script元素的defer、async详解

时间:2015-08-18 22:53:54      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:javascript

1. script with async = "async" and without defer: the browser load the outter-js and DOM in async mode, they are loaded at the same time.
2. script with defer = "defer" and without async: the browser load the DOM first, when load action finished, then load the outter-js.

3. script without defer and without async: when browser meet a outter-js, it begin load the js file, when load action finished, when load the rest of DOM.


test1. async without defer VS without async and defer


<html>
	<head>
		<title>
			async without defer
		</title>
	</head>		
	<body>
	</body>
	
	<script>
	    var beginTime = new Date();
		console.log("Begin Time:"+beginTime.getTime());
	</script>
	
	<script async="async" src="1scriptElement_async.js">
	</script>
	
	<script>
		var endTime = new Date();
		console.log("End Time:"+endTime.getTime());
	</script>
</html>


Begin Time:1439903376420

End Time:1439903376425

<html>
	<head>
		<title>
			without defer and async
		</title>
	</head>		
	<body>
	</body>
	
	<script>
	    var beginTime = new Date();
		console.log("Begin Time:"+beginTime.getTime());
	</script>
	
	<script src="1scriptElement_async.js">
	</script>
	
	<script>
		var endTime = new Date();
		console.log("End Time:"+endTime.getTime());
	</script>
</html>

Begin Time:1439903528064

End Time:1439903528115


test2. defer without async VS without async and defer

<html>
	<head>
		<title>
			 without async and defer 

		</title>
	</head>		
	
	<script>
	    var beginTime = new Date();
		console.log("Begin Time:"+beginTime.getTime());
	</script>
	
	<script src="1scriptElement_async.js">
	</script>
	
	<script>
		hello();
		var endTime = new Date();
		console.log("End Time:"+endTime.getTime());
	</script>
	
	<body>
		<img src="IMG1.JPG">
	</body>
	
	
</html>

Begin Time:1439904005743

hello,world!

End Time:1439904005804


<html>
	<head>
		<title>
			defer without async
		</title>
	</head>		
	
	<script>
	    var beginTime = new Date();
		console.log("Begin Time:"+beginTime.getTime());
	</script>
	
	<script defer="defer" src="1scriptElement_async.js">
	</script>
	
	<script>
		hello();
		var endTime = new Date();
		console.log("End Time:"+endTime.getTime());
	</script>
	
	<body>
		<img src="IMG1.JPG">
	</body>
	
	
</html>

Begin Time:1439904096400

Uncaught ReferenceError: hello is not defined


因为设置defer="defer"后,要等图像加载完成才能下载js,运行hello()时还没有下载js,所以chrome控制台显示错误。


版权声明:本文为博主原创文章,未经博主允许不得转载。

script元素的defer、async详解

标签:javascript

原文地址:http://blog.csdn.net/tsinggao/article/details/47759841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!