Adjuntar un evento body onload con JS
¿Cómo adjunto un evento body onload con JS en un navegador cruzado? Tan simple como esto?
document.body.onload = function(){
alert("LOADED!");
}
7 answers
Esto aprovecha DOMContentLoaded - que se dispara antes de onload - pero le permite mantener toda su discreción...
Ventana.onload-Dean Edwards - La entrada del blog habla más sobre ello - y aquí está el código completo copiado de los comentarios de ese mismo 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;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-05 22:11:11
¿Por qué no usar el propio evento window
onload
?
window.onload = function () {
alert("LOADED!");
}
Si no me equivoco, eso es compatible en todos los navegadores.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-05 22:08:11
Ventana cruzada del navegador.evento de carga
function load(){}
window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-14 11:55:08
document.body.onload
es un navegador cruzado, pero un mecanismo heredado que solo permite una devolución de llamada única (no puede asignarle múltiples funciones).
La alternativa "estándar" más cercana, addEventListener
no es compatible con Internet Explorer (utiliza attachEvent
), por lo que es probable que desee utilizar una biblioteca (jQuery, MooTools, prototype.js, etc.) para abstraer la fealdad entre navegadores para usted.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-26 19:44:32
La idea de Jcalfee314 funcionó para mí - yo tenía un window.onload = onLoad
que significaba que las funciones en <body onload="...">
no estaban siendo llamadas (que no tengo control sobre).
Esto lo arregló:
oldOnLoad = window.onload
window.onload = onLoad;
function onLoad()
{
oldOnLoad();
...
}
Editar: a Firefox no le gustó oldOnLoad = document.body.onload;
, por lo que fue reemplazado por oldOnLoad = window.onload
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-21 17:22:04
Hay varios métodos diferentes que debe usar para diferentes navegadores. Bibliotecas como jQuery le dan una interfaz de navegador que maneja todo por usted, sin embargo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-05 22:02:40
¿Por qué no usar jQuery?
$(document).ready(function(){}))
Hasta donde yo sé, esta es la solución perfecta.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 12:59:48