How to run multiple JavaScript functions when loading a page?
When using several JavaScript libraries on one page, it happens that only one of them works correctly.
This is usually due to a problem of overwriting event handlers: indeed, if the
onload
attribute is set several times (either on thewindow
object in the JavaScript code on the body
element in the code (X) (HTML), only the last definition is taken into account.
Like what:
[...]
<script type="text/javascript">
window.onload = init1;
</script>
</head>
<body onload="init2();">
<!-- Seule init2 sera exécutée au chargement de la page -->
[...]
To avoid this problem, there are several solutions:
- Exploit a framework such as jQuery and several statements
$(document).ready(function() { ... }
) - Consolidate all initializations:
- in the JavaScript code:
window.onload = function() { init1(); init2(); };
- in the (X) HTML code:
<body onload="init1(); init2();">
- in the JavaScript code:
- Use a function that handles adding event handlers to avoid the crash, such as Simon Willison.
- Go through the DOM 2 event handlers / IE.
window.addEventListener("load", fn1)
ReplyDeletewindow.addEventListener("load", fn2)