Header Ads

How to run multiple JavaScript functions when loading a page?

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:
  1. Exploit a framework such as jQuery and several statements $(document).ready(function() { ... } )
  2. Consolidate all initializations:
    • in the JavaScript code:
      window.onload = function() { init1(); init2(); };
    • in the (X) HTML code:
      <body onload="init1(); init2();">
  3. Use a function that handles adding event handlers to avoid the crash, such as Simon Willison.
  4. Go through the DOM 2 event handlers / IE.

1 comment:

  1. window.addEventListener("load", fn1)

    window.addEventListener("load", fn2)

    ReplyDelete

Powered by Blogger.