$(document).ready() Vs. window.onload

2 篇文章 0 订阅
1 篇文章 0 订阅

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.

  1. 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.

  2. $(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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值