一些主流JS框架中DOMReady事件的实现小结

2020-05-19 07:40:28易采站长站整理

// might. Note that this has changed because the build process
// strips all comments — including conditional ones.
if(!dojo.config.afterOnLoad){
document.write(‘<scr’+’ipt defer=”” src=”//:” +=”” onreadystatechange=”if(this.readyState==’complete’){‘ + dojo._scopeName + ‘._loadInit();}”>’
+ ‘</scr’+’ipt>’
);
}
try{
document.namespaces.add(“v”,”urn:schemas-microsoft-com:vml”);
document.createStyleSheet().addRule(“v:*”, “behavior:url(#default#VML)”);
}catch(e){}
}
// FIXME: dojo.unloaded requires dojo scope, so using anon function wrapper.
_handleNodeEvent(“onbeforeunload”, function() {
dojo.unloaded();
});
_handleNodeEvent(“onunload”, function() {
dojo.windowUnloaded();
});
})();

实现思路如下:
如果是Opera或FF3以上版本则直接注册DOMContentLoaded<事件,为保险起见,同时也注册了window.onload事件。
对于webkit则通过轮询document.readyState来实现。
如果是Air则只注册widnow.onload事件。
如果是IE则通过往页面写带defer属性的script并注册其onreadystatechange事件来实现。
Dojo在IE下的实现方案同样无法解决iframe的问题,而由于在FF2 下会有一个非常奇怪的Bug,因此默认只在FF3以上版本上使用DOMContentLoaded事件,同时又给了一个配置 -dojo.config.enableMozDomContentLoaded,如果在FF下将该配置设置为true则依然会使用 DOMContentLoaded来实现,这一点充分考虑到了灵活性。对于webkit的实现,与prototype一样有优化的空间。
五、YUI

(function() {
/*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
// Internet Explorer: use the readyState of a defered script.
// This isolates what appears to be a safe moment to manipulate
// the DOM prior to when the document’s readyState suggests
// it is safe to do so.
if (EU.isIE) {
// Process onAvailable/onContentReady items when the
// DOM is ready.
YAHOO.util.Event.onDOMReady(
YAHOO.util.Event._tryPreloadAttach,
YAHOO.util.Event, true);
var n = document.createElement(‘p’);
EU._dri = setInterval(function() {
try {
// throws an error if doc is not ready
n.doScroll(‘left’);
clearInterval(EU._dri);
EU._dri = null;
EU._ready();
n = null;
} catch (ex) {
}
}, EU.POLL_INTERVAL);
// The document’s readyState in Safari currently will
// change to loaded/complete before images are loaded.
} else if (EU.webkit && EU.webkit < 525) {
EU._dri = setInterval(function() {
var rs=document.readyState;
if (“loaded” == rs || “complete” == rs) {
clearInterval(EU._dri);