What exactly is the difference between the window.onload
event and the onload
event of the body
tag? when do I use which and how shoul
Sorry for reincarnation of this thread again after another 3 years of sleeping, but perhaps I have finally found the indisputable benefit of window.onload=fn1;
over <body onload="fn1()">
. It concerns the JS modules or ES modules: when your onload
handler resides in "classical" JS file (i.e. referred without <script type="module" … >
, either way is possible; when your onload
handler resides in "module" JS file (i.e. referred with <script type="module" … >
, the <body onload="fn1()">
will fail with "fn1() is not defined" error. The reason perhaps is that the ES modules are not loaded before HTML is parsed … but it is just my guess. Anyhow, window.onload=fn1;
works perfectly with modules ...