Dom加载事件cross borwser本机JavaScript代码 [英] Dom loaded event cross borwser native javascript code
本文介绍了Dom加载事件cross borwser本机JavaScript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在没有JavaScript框架的情况下工作,但是我想在加载DOM时调用一个函数。
I'm working without the javascript framework, but I want to call a function just when the DOM is loaded.
我不能/不想要使用<
I can't/don't want to use the attribute 'onload' on the < body > tag.
推荐答案
这是代码:
- 在非IE浏览器中,在IE顶部框架中使用DOMContentLoaded事件
- 使用scroll hack(请参阅_readyIEtop)
-
在IE框架中,只需使用onload
- in non-IE browsers, use DOMContentLoaded event
- in IE top frame use scroll hack (see _readyIEtop)
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery调整IE多一点的代码),但在我的测试中,它运行在onload事件之前。
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);
这篇关于Dom加载事件cross borwser本机JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文