Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach a body onload event with JS

How do I attach a body onload event with JS in a cross browser way? As simple as this?

  document.body.onload = function(){       alert("LOADED!");   } 
like image 255
Robin Rodricks Avatar asked Aug 05 '09 21:08

Robin Rodricks


People also ask

How do you call an onload function in body tag?

The onload attribute fires when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).

Is there an onload function in JavaScript?

In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.

Can I use onload with Div?

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.


2 Answers

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig  function init() {   // quit if this function has already been called   if (arguments.callee.done) return;    // flag this function so we don't do the same thing twice   arguments.callee.done = true;    // kill the timer   if (_timer) clearInterval(_timer);    // do stuff };  /* for Mozilla/Opera9 */ if (document.addEventListener) {   document.addEventListener("DOMContentLoaded", init, false); }  /* for Internet Explorer */ /*@cc_on @*/ /*@if (@_win32)   document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");   var script = document.getElementById("__ie_onload");   script.onreadystatechange = function() {     if (this.readyState == "complete") {       init(); // call the onload handler     }   }; /*@end @*/  /* for Safari */ if (/WebKit/i.test(navigator.userAgent)) { // sniff   var _timer = setInterval(function() {     if (/loaded|complete/.test(document.readyState)) {       init(); // call the onload handler     }   }, 10); }  /* for other browsers */ window.onload = init; 
like image 60
gnarf Avatar answered Oct 08 '22 17:10

gnarf


Why not use window's own onload event ?

window.onload = function () {       alert("LOADED!"); } 

If I'm not mistaken, that is compatible across all browsers.

like image 27
Andreas Grech Avatar answered Oct 08 '22 16:10

Andreas Grech