日期:2014-05-16  浏览次数:20463 次

实现jQuery的document.ready功能js代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>document.ready</title> 
<script type="text/javascript"> 
(function () { 
    var ie = !!(window.attachEvent && !window.opera); 
    var wk = /webkit\/(\d+)/i.test(navigator.userAgent) && (RegExp.$1 < 525); 
    var fn = []; 
    var run = function () { for (var i = 0; i < fn.length; i++) fn[i](); }; 
    var d = document; 
    d.ready = function (f) { 
        if (!ie && !wk && d.addEventListener) 
            return d.addEventListener('DOMContentLoaded', f, false); 
        if (fn.push(f) > 1) return; 
        if (ie) 
            (function () { 
                try { d.documentElement.doScroll('left'); run(); } 
                catch (err) { setTimeout(arguments.callee, 0); } 
            })(); 
        else if (wk) 
            var t = setInterval(function () { 
            if (/^(loaded|complete)$/.test(d.readyState)) 
            clearInterval(t), run(); 
            }, 0); 
    }; 
})(); 
document.ready(function(){ 
    document.getElementById('test').innerHTML = 'document.ready test!'; //找到 
}); 
alert(document.getElementById('test')); //null 没找到 
</script> 
</head> 
<body> 
<div id="test"></div> 
</body> 
</html>