window.onload 與 $(document).ready() 區別

A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){} and <body onload="func();"> are different ways of using the same event.javascript

一個window load 事件觸發條件是你頁面徹底加載時(頁面徹底加載包括DOM內容,異步JS,frames框架,和圖像加載)。你能夠用window.onload = function(){}<body onload="func();"> 添加事件監聽器。css

jQuery $document.ready function event executes a bit earlier than window.onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.html

jQuery $document.ready 函數事件比 window.onload 執行找一點點。一旦頁面DOM加載完成, $document.ready 就會被調用。它不會等待images,frame加載完成才調用。java

From http://stackoverflow.com/questions/3698200/window-onload-vs-document-ready/18843427#18843427jquery

測試代碼以下所示,ready會先行於onload框架

<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="UTF-8"/>   
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
		<title>onload與ready測試</title>
		<style type="text/css">
			
		</style>
		<script type="text/javascript" src="jquery-2.1.4.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				alert('ready');
			});
			
			window.onload=function(){
				alert('load');
			}
			//ready 先行於 onload
		</script>
	</head>
	
	<body>
	</body>
</html>
相關文章
相關標籤/搜索