87,925
社区成员
发帖
与我相关
我的任务
分享
var $ready = function(f){
// 如果Dom加载完毕 那么就直接执行函数
if($ready.done) return f();
// 如果已经绑定了一个函数
if($ready.timer){
// 将下个函数排队
$ready.ready.push(f);
}else{
// 由于firefox的缓存优化有可能onload早于dom加载完毕
window.onload = $isReady;
// 将函数保存起来
$ready.ready = [f];
// 不断的通过$isReady函数去判断是否加载完毕
$ready.timer = setInterval($isReady, 13);
}
};
var $isReady = function(){
// 如果已经完毕 则返回即可
if($ready.done) return false;
// 通过几个元素特性 不断判断document等是否完全加载完毕
if(document && document.getElementsByTagName && document.getElementById
&& document.body){
// 如果完毕. 停止检测时钟. 清空变量 循环执行函数 将done标志置为完毕
clearInterval($ready.timer);
$ready.timer = null;
for(var i = 0; i < $ready.ready.length; i++){
$ready.ready[i]();
}
$ready.ready = null;
$ready.done = true;
}
};
// 使用方法
$ready(function(){
alert('dom is onload');
// DOM已经确保加载完毕,可以进行相关操作
});
而 你说的 相当于把script放到body后面 却是有问题的...
现在FF 浏览器 也实现了 缓存机制 所有其实window.onload 有可能更先去执行的
回楼上的 这个我当然知道 我只是告诉楼主 可以当做原生的onload用
domReady的实现方式很多
也可以用
document && document.getElementsByTagName && document.getElementById && document.body
用setInterval 去不断探取 一样可以达到domReady的效果
并不是就JQ 那么一种方案
var ready=function(readyCall) {
if(document.addEventListener)
document.addEventListener("DOMContentLoaded",function() {
document.removeEventListener("DOMContentLoaded",arguments.callee,false);
readyCall();
},false);
else if(document.attachEvent) {//for IE
if(document.documentElement.doScroll && window.self==window.top) {
(function() {
try {
document.documentElement.doScroll("left");
}catch(ex) {
setTimeout(arguments.callee,5);
return;
}
readyCall();
})();
}else {//maybe late but also for iframes
document.attachEvent("onreadystatechange",function() {
if(document.readyState==="complete") {
document.detachEvent("onreadystatechange", arguments.callee);
readyCall();
}
});
}
}
}
$(document).ready 是Jquery框架里的东西 代替原生javascript的 window.onload事件用