<!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>判断DOM树创建完毕</title> </head> <body> <script type="text/javascript"> // 判断DOM树创建完毕 function domReady(fn) { var d = window.document, done = false, // 只执行一次用户的回调函数init() init = function () { if (!done) { done = true; fn(); } }; (function () { try { // DOM树未创建完之前调用doScroll会抛出错误 d.documentElement.doScroll(‘left‘); } catch (e) { //延迟再试一次~ setTimeout(arguments.callee, 50); return; } // 没有错误就表示DOM树创建完毕,然后立马执行用户回调 init(); })(); //监听document的加载状态 d.onreadystatechange = function() { // 如果用户是在domReady之后绑定的函数,就立马执行 if (d.readyState == ‘complete‘) { d.onreadystatechange = null; init(); } }; } domReady(function(){ // alert(‘测试‘); var data = document.getElementById(‘data‘); data.innerHTML = ‘测试‘; }); </script> <div id="data">原内容</div> </body> </html>
原文:http://www.cnblogs.com/joden/p/4095179.html