Merge pull request #2573 from kentaromiura/no-sniff-2-of-3-oldie-clonenode-bug
[mootools.git] / Source / Utilities / DOMReady.js
blob9327bb1df8aa0cf40fff965f5e7315a6bb71a9df
1 /*
2 ---
4 name: DOMReady
6 description: Contains the custom event domready.
8 license: MIT-style license.
10 requires: [Browser, Element, Element.Event]
12 provides: [DOMReady, DomReady]
14 ...
17 (function(window, document){
19 var ready,
20         loaded,
21         checks = [],
22         shouldPoll,
23         timer,
24         testElement = document.createElement('div');
26 var domready = function(){
27         clearTimeout(timer);
28         if (ready) return;
29         Browser.loaded = ready = true;
30         document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
32         document.fireEvent('domready');
33         window.fireEvent('domready');
36 var check = function(){
37         for (var i = checks.length; i--;) if (checks[i]()){
38                 domready();
39                 return true;
40         }
41         return false;
44 var poll = function(){
45         clearTimeout(timer);
46         if (!check()) timer = setTimeout(poll, 10);
49 document.addListener('DOMContentLoaded', domready);
51 /*<ltIE8>*/
52 // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
53 // testElement.doScroll() throws when the DOM is not ready, only in the top window
54 var doScrollWorks = function(){
55         try {
56                 testElement.doScroll();
57                 return true;
58         } catch (e){}
59         return false;
61 // If doScroll works already, it can't be used to determine domready
62 //   e.g. in an iframe
63 if (testElement.doScroll && !doScrollWorks()){
64         checks.push(doScrollWorks);
65         shouldPoll = true;
67 /*</ltIE8>*/
69 if (document.readyState) checks.push(function(){
70         var state = document.readyState;
71         return (state == 'loaded' || state == 'complete');
72 });
74 if ('onreadystatechange' in document) document.addListener('readystatechange', check);
75 else shouldPoll = true;
77 if (shouldPoll) poll();
79 Element.Events.domready = {
80         onAdd: function(fn){
81                 if (ready) fn.call(this);
82         }
85 // Make sure that domready fires before load
86 Element.Events.load = {
87         base: 'load',
88         onAdd: function(fn){
89                 if (loaded && this == window) fn.call(this);
90         },
91         condition: function(){
92                 if (this == window){
93                         domready();
94                         delete Element.Events.load;
95                 }
96                 return true;
97         }
100 // This is based on the custom load event
101 window.addEvent('load', function(){
102         loaded = true;
105 })(window, document);