document.ready como funcionalidad en Javascript? [duplicar]

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() función.

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

preguntado el 31 de julio de 12 a las 12:07

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. -

jQuery is actually open source, so if you want that exact behavior, go and copy that part - it's plain javascript. -

@Felix: Could you turn that into an answer? -

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. -

4 Respuestas

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/

Respondido 31 Jul 12, 12:07

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>

Respondido 31 Jul 12, 12:07

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

Respondido 31 Jul 12, 13:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.