Cannot understand this code



I am reading a Javascript book in which the below code was given. I’m unable to understand it. The purpose of this code is to define an onLoad() function that registers a function to be run when the document finishes loading.

I also think that the last one should be " else (window.attachEvent)" instead of "else if (window.attachEvent)"
I also don’t know if “.loaded” is an event…

Can someone plz explain what is going on in this code step-by-step?

// Register the function f to run when the document finishes loading. 
// If the document has already loaded, run it asynchronously ASAP.
function onLoad(f) {
  if (onLoad.loaded) // If document is already loaded
    window.setTimeout(f, 0); // Queue f to be run as soon as possible 
 else if (window.addEventListener) // Standard event registration method
    window.addEventListener("load", f, false);
 else if (window.attachEvent) // IE8 and earlier use this instead
   window.attachEvent("onload", f);
// Start by setting a flag that indicates that the document is not loaded yet. 
onLoad.loaded = false;
// And register a function to set the flag when the document does load. 
onLoad(function() { onLoad.loaded = true; });


That book is rather dated, but this is the sort of code we might find buried in the early JavaScript libraries, and abstracted to surface something like,

jQuery(document).ready(function () {});

The function in the book is the sort of code that libraries are built around to bridge the gap between two worlds during the browser wars. IE in one, and the rest in the other.


was for IE,


was for the rest.

There was no else, though, since that would assume a foreign and unknown user agent. The default action is no action.


Yeah you are right. The book is very old (published in 2011) and things have changed but it’s still a good book for a deep understanding of the language.

I know that the same code can be written in jQuery also. I was just trying to understand what is he doing in this code…

Yeah we have to write code including different functions and methods just for IE users which is a little irritating.

I didn’t get it. I thought that the flow was If (onLoad.loaded) run f, else if .addEventListener is there, use that else, use .attachEvent

I also did not get the statements written below too but it doesn’t matter coz I’ll probably never use it.

Thanks :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.