Fixes #2715 - Adding Microsoft Edge UA string support to Browser.
[mootools.git] / Source / Utilities / DOMReady.js
blob4ba7c6397884bd70a75f05eb1d3a969fc271a0f9
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) {
29                 Browser.loaded = ready = true;
30                 document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
31                 document.fireEvent('domready');
32                 window.fireEvent('domready');
33         }
34         // cleanup scope vars
35         document = window = testElement = null;
38 var check = function(){
39         for (var i = checks.length; i--;) if (checks[i]()){
40                 domready();
41                 return true;
42         }
43         return false;
46 var poll = function(){
47         clearTimeout(timer);
48         if (!check()) timer = setTimeout(poll, 10);
51 document.addListener('DOMContentLoaded', domready);
53 /*<ltIE8>*/
54 // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
55 // testElement.doScroll() throws when the DOM is not ready, only in the top window
56 var doScrollWorks = function(){
57         try {
58                 testElement.doScroll();
59                 return true;
60         } catch (e){}
61         return false;
63 // If doScroll works already, it can't be used to determine domready
64 //   e.g. in an iframe
65 if (testElement.doScroll && !doScrollWorks()){
66         checks.push(doScrollWorks);
67         shouldPoll = true;
69 /*</ltIE8>*/
71 if (document.readyState) checks.push(function(){
72         var state = document.readyState;
73         return (state == 'loaded' || state == 'complete');
74 });
76 if ('onreadystatechange' in document) document.addListener('readystatechange', check);
77 else shouldPoll = true;
79 if (shouldPoll) poll();
81 Element.Events.domready = {
82         onAdd: function(fn){
83                 if (ready) fn.call(this);
84         }
87 // Make sure that domready fires before load
88 Element.Events.load = {
89         base: 'load',
90         onAdd: function(fn){
91                 if (loaded && this == window) fn.call(this);
92         },
93         condition: function(){
94                 if (this == window){
95                         domready();
96                         delete Element.Events.load;
97                 }
98                 return true;
99         }
102 // This is based on the custom load event
103 window.addEvent('load', function(){
104         loaded = true;
107 })(window, document);