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

173 阅读1分钟

页面上的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”或扫描下方二维码关注微信公众号,第一时间获取最新文章(^_^)

谈谈IT