jQuery的domReady

时间:2022-09-20 20:46:20
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery的DOMready</title>
<script>
var domReady = function(fn){
var completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
fn();
}; // 如果dom已经准备好了,那就开始咯。setTimeout第三个参数是为了传入同样的参数。为什么要setTimeout,是为了触发事件。
if ( document.readyState === "complete" ) {
setTimeout( domReady,0,fn ); } else {
document.addEventListener( "DOMContentLoaded", completed, false );
// 保险起见加个load事件咯。有时候因为浏览器缓存的原因导致,load比DOMContentLoaded执行还早。
window.addEventListener( "load", completed, false );
} }
domReady(function(){
alert(document.querySelectorAll(".test")[0].innerHTML);
});
</script>
</head>
<body>
jQuery的DOMready
<div class="test">dom ready?</div>
</body>
<script> </script>
</html>