4

Possible Duplicate:
$(document).ready equivalent without jQuery

I have a framework-less javascript that executes on load:

function myJs() {    
   // some code
}
window.load = myJs;

But this causes a delay in the execution of the script. I want to be able to execute this script as soon as the document is ready to be manipulated even before the page has completely finished loading. How can this be done in a cross browser compatible way? In other words how can the:

$(document).ready(function() {  
   //
});

of jQuery be said in plain JS?

Community
  • 1
  • 1
Thomas
  • 43
  • 1
  • 1
  • 3

6 Answers6

6

I have made an implementation (based on the one found in jQuery) that you can use: http://github.com/jakobmattsson/onDomReady/blob/master/ondomready.js

Jakob
  • 23,205
  • 7
  • 44
  • 55
  • Hey, very new to js jere. Could you please show how to implement this. Would I do something like: onDomReady(function() { //code here }); ? – Thomas Sep 28 '10 at 14:50
  • you are exactly right :) – Jakob Sep 28 '10 at 14:52
  • You can call onDomReady several times with different code-snippets if you want to as well. They will all be executed in order. And in case it isn't already clear, you must include my code before you make that call. Also, if you want to change the name of the function ("onDomReady"), do it on line 10 only. – Jakob Sep 28 '10 at 14:57
  • worked like a charm, thanks so much! – Thomas Sep 28 '10 at 15:19
1
//old IE
document.onreadystatechange = function() {
   if (this.readyState === "complete"){
      //whatev
   }
};


//for everyone else
document.addEventListener("DOMContentLoaded", function () {
  //whatev
  }, false);
Conner
  • 27,462
  • 8
  • 47
  • 72
AutoSponge
  • 1,426
  • 10
  • 7
  • The only version of IE that natively supports `DOMContentLoaded` is 9. – MooGoo Sep 28 '10 at 14:37
  • changed to onDOMContentLoaded for older version of IE, thanks for the reminder. – AutoSponge Sep 28 '10 at 14:37
  • Not 100% certain but pretty sure IE <9 does not support the event even with `on` perpended to it. And I think you meant to put the 'on' in the `attachEvent` function. – MooGoo Sep 28 '10 at 15:04
0

It's actually not that bad. You need a way to add events to document, and the knowledge of what those events should be. Using the standard addEvent function

function addEvent( obj, type, fn )
{
 if (obj.addEventListener)
 {
   obj.addEventListener( type, fn, false );
 }
 else if (obj.attachEvent)
 {
  obj["e"+type+fn] = fn;
  obj[type+fn] = function() { return obj["e"+type+fn]( window.event ); };
  obj.attachEvent( "on"+type, obj[type+fn] );
 }
}

You can do the following:

// IE
addEvent(document, 'DOMContentLoaded', function() {
    alert('ready');
});

// Other
addEvent(document, 'onreadystatechange', function() {
    if (document.readyState == 'complete')
        alert('ready');
});

// For demonstration purposes, show a 'load' event
addEvent(window, 'load', function() {
    alert('load');
});

The IE event handler will simply not fire in other browsers, and vice-versa.

Ryan Kinal
  • 16,165
  • 4
  • 41
  • 63
0

But this causes a delay in the execution of the script. I want to be able to execute this script as soon as the document is ready to be manipulated even before the page has completely finished loading.

Well there are three ways you can approach this problem:

  1. As a few have already suggested, you can draw inspiration from the jQuery source code and integrate that into your script. (I recommend watching Paul Irish on jQuery Source and looking at JS Libs Deconstructed.
  2. You can put the function call at the end of the body tag instead of in the head tag. This allows for all DOM elements to be loaded before the script starts.
  3. If you don't need to work with the DOM whatsoever, you could just make it a self-executing function so you don't have to wait for anything. (function startNow(){}())
Moses
  • 8,741
  • 5
  • 39
  • 61
-1

Put

function myJs() {    
   // some code
}

in the <head></head> and

window.load = myJs;

Just before </body>

Shikiryu
  • 9,920
  • 6
  • 47
  • 74
  • 1
    Can you explain instead of -1 ing me. Maybe I'll learn something. – Shikiryu Sep 28 '10 at 14:18
  • `.load` is different from `.ready` - `.load` waits for all images, scripts, outside resources, etc. to be loaded before executing, while `.ready` is executed once all DOM resources are loaded (i.e. the HTML structure). Thus, if a page has both `.ready` and `.load`, `.ready` will execute before `.load` – Ryan Kinal Sep 28 '10 at 14:41
  • 1
    I see and after reflection (and after I re-read the question, that I misunderstood) I agree. But, then, @Josh Stodola, instead of this crappy and useless answer and -1 ing everyone, why not answering the guy directly with this explanation ? :) I'm pretty sure that's the goal of stackoverflow to answer and explain (even if i just registered) – Shikiryu Sep 28 '10 at 14:46
  • @Couchenos Fine, I just went and up-voted two of your answers elsewhere that were good answers. This is not a good answer, so I down-voted it. Big deal. I don't need to explain myself... it's pretty obvious that this answer is incorrect and misleading. – Josh Stodola Sep 28 '10 at 14:57
  • @Josh Stodola : Excuse me if it seems like it but I don't blame you for the -1, but for a comment like "Ummmmmmmmmmm no" and no explanation. It may seem obvious to you but not for everyone who's trying to help ;). Even more, if you don't give a proper answer to the original asker! Still my answer is wrong, it doesn't answer the question I misread, so I deserved it. I don't care about my "score" or what ever it's called. – Shikiryu Sep 28 '10 at 15:07
  • I did the original asker a favor by down-voting this and up-voting a better answer. If you want to know why this doesn't work, TRY IT! Don't just spew out an answer if you don't know what you're talking about. – Josh Stodola Sep 28 '10 at 15:19
  • Excuse me but, what I wrote works. Alright, **it doesn't answer the question** and may be ugly but, still, it works. And, yes, I tried. And please, no rage. BTW, thanks Ryan Kinal :) – Shikiryu Sep 28 '10 at 15:30
  • Define "works". There is no `window.load` event. And even if there was, assigning it right before `

    ` does *nothing*. I am done arguing with you about this...

    – Josh Stodola Sep 28 '10 at 16:07
  • Indeed, this is very simple. Assigning a function to `window.load` will do *nothing*. You need to use `window.onload`. – MooGoo Sep 28 '10 at 16:38
-2

you can create a function where ever you wont, the call it in

`<body onLoad="function();">`
Fribu - Smart Solutions
  • 2,675
  • 3
  • 26
  • 57