现在,我们来研究一下如何解决这个问题,解决方法就是在DOM加载完毕之后就执行程序。
先介绍两个人。一,jquery的作者:JohnResig;二,javascript的世界级大师:deanedwards。(大家要记住这两位天才!)
jquery里有专门解决DOM加载的函数$(document).ready()(简写就是$(fn)),非常好用!JohnResig在《ProJavaScriptTechniques》里,有这样一个方法处理DOM加载,原理就是通过document&&document.getElementsByTagName&&document.getElementById&&document.body去判断Dom树是否加载完毕。代码如下:
复制代码 代码如下:
functiondomReady(f){
//如果DOM加载完毕,马上执行函数
if(domReady.done)returnf();
//假如我们已增加一个函数
if(domReady.timer){
//把它加入待执行的函数清单中
domReady.ready.push(f);
}else{
//为页面加载完成绑定一个事件,
//为防止它最先完成.使用addEvent(下面列出).
addEvent(window,“load”,isDOMReady);
//初始化待执行的函数的数组
domReady.ready=[f];
//经可能快地检查Dom是否已可用
domReady.timer=setInterval(isDOMReady,13);
}
}
//检查Dom是否已可操作
functionisDOMReady(){
//假如已检查出Dom已可用,忽略
if(domReady.done)returnfalse;
//检查若干函数和元素是否可用
if(document&&document.getElementsByTagName&&document.getElementById&&document.body){
//假如可用,停止检查
clearInterval(domReady.timer);
domReady.timer=null;
//执行所有等待的函数
for(vari=0;i<domReady.ready.length;i++)
domReady.ready[i]();
//记录在此已经完成
domReady.ready=null;
domReady.done=true;
}
}
//由DeanEdwards在2005所编写addEvent/removeEvent,
//由TinoZijdel整理
//http://dean.edwards.name/weblog/2005/10/add-event/
//优点是1.可以在所有浏览器工作;
//2.this指向当前元素;
//3.综合了所有浏览器防止默认行为和阻止事件冒泡的的函数
//缺点就是仅在冒泡阶段工作
functionaddEvent(element,type,handler){
//assigneacheventhandlerauniqueID
if(!handler.$$guid)handler.$$guid=addEvent.guid++;
//createahashtableofeventtypesfortheelement
if(!element.events)element.events={};
//createahashtableofeventhandlersforeachelement/eventpair
varhandlers=element.events[type];
if(!handlers){
handlers=element.events[type]={};
//storetheexistingeventhandler(ifthereisone)
if(element["on"+type]){
handlers[0]=element["on"+type];
}
}
//storetheeventhandlerinthehashtable
handlers[handler.$$guid]=handler;
//assignaglobaleventhandlertodoallthework
element["on"+type]=handleEvent;
};
//acounterusedtocreateuniqueIDs
addEvent.guid=1;
functionremoveEvent(element,type,handler){
//deletetheeventhandlerfromthehashtable
if(element.events&&element.events[type]){
deleteelement.events[type][handler.$$guid];
}
};
functionhandleEvent(event){
varreturnValue=true;
//grabtheeventobject(IEusesaglobaleventobject)
event=event||fixEvent(window.event);
//getareferencetothehashtableofeventhandlers
varhandlers=this.events[event.type];
//executeeacheventhandler
for(variinhandlers){
this.$$handleEvent=handlers[i];
if(this.$$handleEvent(event)===false){
returnValue=false;
}
}
returnreturnValue;
};
functionfixEvent(event){
//addW3Cstandardeventmethods
event.preventDefault=fixEvent.preventDefault;
event.stopPropagation=fixEvent.stopPropagation;
returnevent;
};
fixEvent.preventDefault=function(){
this.returnValue=false;
};
fixEvent.stopPropagation=function(){
this.cancelBubble=true;
};
还有一个估计由几个外国大师合作写的,实现同样功能。
复制代码 代码如下:
/*
*(c)2006JesseSkinner/DeanEdwards/MatthiasMiller/JohnResig
*SpecialthankstoDanWebb'sdomready.jsPrototypeextension
*andSimonWillison'saddLoadEvent
*
*Formoreinfo,see:
*http://www.thefutureoftheweb.com/blog/adddomloadevent
*http://dean.edwards.name/weblog/2006/06/again/
*http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
*http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*
*
*Touse:calladdDOMLoadEventoneormoretimeswithfunctions,ie:
*
*functionsomething(){
*//dosomething
*}
*addDOMLoadEvent(something);
*
*addDOMLoadEvent(function(){
*//dootherstuff
*});
*
*/
addDOMLoadEvent=(function(){
//createeventfunctionstack
varload_events=[],
load_timer,
script,
done,
exec,
old_onload,
init=function(){
done=true;
//killthetimer
clearInterval(load_timer);
//executeeachfunctioninthestackintheordertheywereadded
while(exec=load_events.shift())
exec();
if(script)script.onreadystatechange='';
};
returnfunction(func){
//iftheinitfunctionwasalreadyran,justrunthisfunctionnowandstop
if(done)returnfunc();
if(!load_events[0]){
//forMozilla/Opera9
if(document.addEventListener)
document.addEventListener("DOMContentLoaded",init,false);
//forInternetExplorer
/*@cc_on@*/
/*@if(@_win32)
document.write("<scriptid=__ie_onloaddefersrc=//0></scr"+"ipt>");
script=document.getElementById("__ie_onload");
script.onreadystatechange=function(){
if(this.readyState=="complete")
init();//calltheonloadhandler
};
/*@end@*/
//forSafari
if(/WebKit/i.test(navigator.userAgent)){//sniff
load_timer=setInterval(function(){
if(/loaded|complete/.test(document.readyState))
init();//calltheonloadhandler
},10);
}
//forotherbrowserssetthewindow.onload,butalsoexecutetheoldwindow.onload
old_onload=window.onload;
window.onload=function(){
init();
if(old_onload)old_onload();
};
}
load_events.push(func);
}
})();
【Dom加载让图片加载完再执行的脚本代码】相关文章: