My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, September 18, 2006

too much simple DOMContentLoaded solution ?

Dean Edwards closed comments in this page (sorry Dean) , but I wonder if there is a real example page where this alternative way to implement DOMContentLoaded doesn't work as expected (please post me one !!!).

My simple solution is this one, anonymous function with multiple callbacks after document.body is not undefined.

(function(){if(document.body){for(var i=0;i<arguments.length;i++)arguments[i]();}else setTimeout(arguments.callee,1)})
(initLightbox, otherFunc, somethingElse, init);

Just 2 simple lines of code, but for some reason it shouldn't work correctly in some case.

Then, while my test page doesn't fail this method, at least with my browsers, I'd like to know when this way shouldn't work correctly or when this way should work (I always prefere to reduce JS size then if generic cases work correctly with this method to implement DOMContentLoaded I'll prefere this one).

Can anyone explain me what's up when this method fail ? Thank you.


kentaromiura said...

try this, split the page in 2 parts, without page cache enabled,
make a long-time-consuming task in the middle (3 big nested for) and try to get the value of something in the beggining, in the middle and in the end of the body with your method.
it shouldn't work (remember to flush data and disable the caching of the page).

Andrea Giammarchi said...

finally the problem is this one !!!

thank you kenta, I usually never write something while I've not created runtime all page content (1 echo with every my php scripts ...) then I didn't view the problem that was in front of me!

You're damn right, as was Dean Edwards, and here there's the example that shows as my solution isn't absolutely usefull.

Example Page - anonymous function fail

Thank you again!

kentaromiura said...

you're welcome, big sboron.
[I think this term should go in the jargon file]
;) seems that you understand my english better then my macaronise ..

Andrea Giammarchi said...


Anonymous said...

As kentaromiura has pointed out, detecting the presence of the document body is not enough. You also need the contents of the body to be loaded and parsed for a complete DOM.

Andrea Giammarchi said...

Yes Dean, I know :)

You could re-open your comments in your page, adding this link for every developer that ask about document.body ;)

See you and please view my last post:
a better DOMContentLoaded ?