使用jQuery在DOM或window加载后执行动作

页面上的javascript执行,除了用户主动交互的事件外,都是在DOM加载完成或window完全加载后执行的(甚至连定时事件也是在此时开始计时)。以下分别分析jQuery针对这两种情况的处理。

使用ready方法定义在DOM被加载后执行的动作

在DOM被加载后执行,不必等要页面元素都渲染完。

三种语法

// Standard.
jQuery(document).ready(function () { alert('DOM is ready!'); });
// Shortcut, but same thing as above.
jQuery(function () { alert('No really, the DOM is ready!'); });
// Shortcut with fail-safe usage of $. Keep in mind that a reference
// to the jQuery function is passed into the anonymous function.
jQuery(function ($) {
alert('Seriously its ready!');
// Use $() without fear of conflicts.
});

其中

jQuery(function () { alert('No really, the DOM is ready!'); });

可能会和插件冲突,所以像下面这样加个$比较好

jQuery(function ($) {
alert('Seriously its ready!');
// Use $() without fear of conflicts.
});

为了保证DOM中的元素在ready方法前真的完全加载了,需要将css文件放在jQuery代码的前面,因为有些css伪类会处理或添加标签。

使用load方法定义在window完全加载后执行的动作

将window对象作为参数传给jQuery方法,调用load方法,可以定义在window完全加载后要执行的动作。此时,所有的外部文件都加载完了(当然,图片可能渲染完也可能在渲染中)

// Pass window to the jQuery function and attach
// event handler using the load() method shortcut.
jQuery(window).load(function(){ alert('The page and all its assets are loaded!'); });

欢迎扫描下方二维码关注微信公众号【谈谈IT】,第一时间获取最新文章。
欢迎关注同名公众号

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值