window.onload及dom ready測試

測試代碼段一:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="http://www.twitter.com/test.css">
	<script>
		console.log('loading script content.')

		window.onload = function  () {
			console.log('onload 1.')
		}

		document.addEventListener('DOMContentLoaded',function(){
			console.log('dom is ready.');
		});

		addOnload(function(){
			console.log('addOnload 1.');
		});

		addOnload(function(){
			console.log('addOnload 2.');
		});

		addOnload(function(){
			console.log('addOnload 3.');
		});


		function addOnload(func){
			var last = window.onload;
			window.onload = function(){
				if(last) last();

				func();
			}

		}
	</script>

</head>
<body>

	<img src="http://www.twitter.com/test.jpg">

</body>
</html>

故意連接到牆外,測試結果以下:
1. 第6行會阻塞第7行, (放在script前的link標籤會阻塞script,若是把link放在script以後,則不會阻塞) javascript

2. body中的img標籤會阻塞window.onload事件。 css

3. body中的img標籤不會阻塞dom ready事件。 html

二。 測試代碼段2. java

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="underscore.js"></script>
	<script>
		(function(global){
			var funcs = [];

			document.addEventListener('DOMContentLoaded',function(){
				console.log('dom is ready.');
				_(funcs).each(function(f){
					f();
				})

			});

			global.addOnReady = function(f){
				funcs.push(f);
			}
		})(window);

		window.onload = function(){
			console.log('window onload.');
		};

		addOnReady(function(){console.log('ready 1.')});
		addOnReady(function(){console.log('ready 2.')});
		addOnReady(function(){console.log('ready 3.')});

	</script>

</head>
<body>

	<img src="http://www.twitter.com/test.jpg">
	<script type="text/javascript">
		addOnReady(function(){console.log('ready 4.')});
	</script>
</body>
</html>

1. body中的img標籤不會阻塞img標籤後面的script
2. dom ready事件無視img標籤,在頁面打開瞬間控制檯會打印出ready 1, ready 2 ready 3 ready 4!

代碼段二的輸出結果以下:

dom is ready.
onload.html:28 ready 1.
onload.html:29 ready 2.
onload.html:30 ready 3.
onload.html:39 ready 4.
onload.html:37 GET https://www.twitter.com/test.jpg net::ERR_CONNECTION_TIMED_OUT
onload.html:25 window onload. dom

相關文章
相關標籤/搜索