当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript IE中的DOM ready应用技巧

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript IE中的DOM ready应用技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 204 ::
收藏到网摘: n/a

当我们想在页面加载之后执行某个函数,肯定会想到onload了 但onload在浏览器看来,就是页面上的东西全部都加载完毕后才能发生,但那就为时已晚了。 如果只需要对DOM进行操作,那么这时就没必要等到页面全部加载了。我们需要更快的方法。
Firefox有DOMContentLoaded事件可以轻松解决,可惜的就是IE没有。
MSDN关于JSCRIPT的一个方法有段不起眼的话,当页面DOM未加载完成时,调用doScroll方法时,会产生异常。那么我们反过来用,如果不异常,那么就是页面DOM加载完毕了!
复制代码 代码如下:

function IEContentLoaded (w, fn) {
var d = w.document, done = false,
// only fire once
init = function () {
if (!done) {
done = true;
fn();
}
};
// polling for no errors
(function () {
try {
// throws errors until after ondocumentready
d.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
// no errors, fire
init();
})();
// trying to always fire before onload
d.onreadystatechange = function() {
if (d.readyState == 'complete') {
d.onreadystatechange = null;
init();
}
};
}

这个函数是Diego Perini在07年就发布了这个方法,
而且获得了广泛认同,以至于现在许多开源框架都是借鉴这种方法,譬如JQuery中的ready。
如果以后需要用到IE的DomReady,就是他了。
用法:
IEContentLoaded( document.getElementById("test") , test );
function test(){ }