gui*_* 桂林 32 javascript domready
在jquery $(document).ready(function)或$(function)中,如果没有jquery,我怎么能做同样的事情,我需要浏览器兼容,并且允许附加多个函数.
Pis*_*3.0 24
这是jQuery包装你正在寻找的函数的方式 - 代码片段不需要jQuery,并且是跨浏览器兼容的.我用yourcallback
- 你需要定义的所有调用jQuery.ready().
这里发生了什么:
DOMContentLoaded
定义函数,该函数将在DOMContentLoaded事件触发时使用 - 它确保仅调用一次回调.document.addEventListener
/ document.attachEvent
)并将回调绑定到它(IE和普通浏览器不同,加上onload回调)从jQuery 1.4.3开始,函数bindReady()和DOMContentLoaded:
/*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
// Cleanup functions for the document ready method
// attached in the bindReady handler
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
//jQuery.ready();
yourcallback();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
//jQuery.ready();
yourcallback();
}
};
}
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
//return setTimeout( jQuery.ready, 1 );
// ^^ you may want to call *your* function here, similarly for the other calls to jQuery.ready
setTimeout( yourcallback, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
//window.addEventListener( "load", jQuery.ready, false );
window.addEventListener( "load", yourcallback, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", yourcallback );
}
Run Code Online (Sandbox Code Playgroud)
这是51行纯JavaScript代码,只是为了可靠地注册事件.据我所知,没有比较简单的方法了.去展示像jQuery这样的包装器有什么用处:它们包含功能嗅探和丑陋的兼容性问题,以便您可以专注于其他事情.
<html>
<head>
<script>
var ready = function (f) {
(/complete|loaded|interactive/.test(document.readyState)) ?
f() :
setTimeout(ready, 9, f);
};
</script>
</head>
<body>
<script>
ready(function () {
alert('DOM Ready!');
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19218 次 |
最近记录: |