0

I have a requirement that states to use only plain JavaScript and not jQuery. I need to initialize some variables(using some function) as soon as the DOM is loaded and not when the page has fully loaded. In short it should not wait for the whole page to load. In jQuery it can be very easily done using document.ready() function.

Is it possible to implement it in JavaScript using any function?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gaurav Sachdeva
  • 652
  • 1
  • 10
  • 23
  • 3
    No, the callback passed to `document.ready()` is executed as soon as the **DOM loaded**. If you just want to execute some code when the page starts loading, put it in the `head`. If you would provide some example, we could help you better. BUt if you really want the same functionality, just put the script at the end of the `body`. – Felix Kling Jul 31 '12 at 11:33
  • jQuery is actually open source, so if you want that exact behavior, go and copy that part - it's plain javascript. – Niko Jul 31 '12 at 11:35
  • 1
    @Felix: Could you turn that into an answer? – Niklas B. Jul 31 '12 at 11:36
  • i just corrected the question....i need that functionality as soon as the DOM is loaded....as you guys mentioned....thanks.....i just need to implement it using javascript and not jquery. – Gaurav Sachdeva Jul 31 '12 at 11:37
  • 1
    This answer explains that http://stackoverflow.com/a/1207005/759019 – Anirudh Ramanathan Jul 31 '12 at 11:38

4 Answers4

2

a "practical" way is just placing a script block before the end of the document (even is not really equivalent to domready)

  ...
  <script>...</script>
  </body>
</html>

or use one of various pure-js implementation of DomReady event, like http://snipplr.com/view/6029/domreadyjs/

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

It's sometimes achieved like this

<body>
<!--
All your html tags here
....
....
-->



    <script type="text/javascript">
      //this should execute after the above tags and elements have rendered
    </script>
</body>
codingbiz
  • 26,179
  • 8
  • 59
  • 96
0

You can use DOMContentLoaded event if supported:

MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/hh868490.aspx

MDN: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded

Andrew D.
  • 8,130
  • 3
  • 21
  • 23
0

if you realy want to wait for "ready event" you can for example use that kind of thing :

    (function(w,evt,fn){
        if (w.addEventListener){// W3C DOM
            w.addEventListener(evt,fn,false);
        }
        else if (w.attachEvent) { // IE DOM
            w.attachEvent("on"+evt, fn);
        }

    })(window,'load',function(){
       // your code here
    });

but it's indeed better to simply use a well placed 'script' tag as your code will probably work and start sooner

vor
  • 91
  • 3