0

I have the following problem: I've got a website that can't have dependencies to javascript-files. I want to have the same function as $(document).ready() in jquery. How would that look like? Thanks.

KJYe.Name 葉家仁
  • 16,133
  • 5
  • 46
  • 61
Espen Schulstad
  • 2,095
  • 3
  • 19
  • 30
  • that's abit tough to do in javascript, but an easier alternative is to use `window.onload` but they are not the samething. – KJYe.Name 葉家仁 Apr 01 '11 at 14:27
  • possible duplicate of [javascript:how to write $(document).ready like event without jquery](http://stackoverflow.com/questions/3989095/javascripthow-to-write-document-ready-like-event-without-jquery) and [document.ready equivalent without jquery](http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Piskvor left the building Apr 01 '11 at 15:14

4 Answers4

4

onLoad works, but it waits until all images and stuff are loaded. If you just want it to run when the DOM is ready, you can do this (found here):

// Create onDomReady event
window.onDomReady = function(f){
    if(document.addEventListener){
        document.addEventListener("DOMContentLoaded", f, false);
    }
    // For IE
    else{
        document.onreadystatechange = function(){
            if(document.readyState == "interactive"){
                f();
            }
        };
    }
};

// Attach a callback to onDomReady
window.onDomReady(function(){
    alert("The DOM is ready!");
});
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
2

You could just look at the jQuery source code. If you want a simple "emulation", just include/call your JavasScript as the last element of <body>

   <!-- ... start of your HTML document -- -->
   <script type="text/javascript">
      likeDocumentReady();
    </script>
  </body>
</html>
RoToRa
  • 34,985
  • 10
  • 64
  • 97
1

Before jQuery onLoad was a common practice, a much detailed answer in this link where you can check for cross browser solution.

http://www.javascriptkit.com/dhtmltutors/domready.shtml

Chohdry
  • 11
  • 2
-1

I guess you're looking for the onload event. But yes123 is right, you should start accepting answers.

window.onload = function() {
    // yadda
}
Bjorn
  • 4,822
  • 1
  • 18
  • 34