on the basis of functionality, $().ready() ==window.onload
all content embeded inside them will be executed once page loaded. while, some advantages of $().ready() comparing with straightly using built-in JavaScript function.
Javascript will not execute its corresponding event function until all content (e.g DOM,image, object, stylesheet…) loaded.
To the ready() which means that event will occur once HTML document (only DOM loaded)has been loaded.$(document).ready() which can be used multiple times without any else interference. But window.onload not like that, actually, the previous called function will be crashed by latter functions.
First of all, let’s have one example about window.onload event to see the result of event
<script src="../../scripts/jquery3.js"></script>
</head>
<body>
<script type="text/javascript">
// let's take two test examples as experimental usage.
function func1(){
alert('This is the first called function');
}
function func2() {
alert('This is the second called function');
}
window.onload=func1;
window.onload=func2;
</script>
Well, a trick method to avoid such problem provided by Simon Willison as below.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
addLoadEvent(func1);
addLoadEvent(func2);
otherwise, a not-bad way that is:
window.onload=function{
func1();
func2();
}
//go this way if just a few number of such onload events //and no further consideration later on.
In short words, jQuery abstract all troublesome with JavaScript away
// jQuery snippet of code as below.
$(document).ready(function(){
func1();
func2();
})
A recap to above.
- Event fires up once dom loaded comparing to all content loaded of window.onload.
- Execute multiple times wrapped in $(function(){}) without additional interference.
引用了DOM Scripting
Web Design with JavaScript and the Document Object Model 和 锋利的jQuery.