1

I had this script to open and close my side menu, it had an HTML built-in event handler. Then I read that built-in event handlers are old-fashioned. So I reworked it to pure JS.

I made my own event handler, which should've worked, but it returned an error: Uncaught TypeError: Cannot set property 'onclick' of null.

Then I read here that maybe I should add to JS:

window.onload = function(){ 
    // your code 
};

I added the function and it worked.

But then it suddenly stopped working after I added another JS for an accordion with the same window.onload since it didn't want to work without the function or when <script> wasn't inside the <head>.

I'm new to JS. Can you help me? Is it possible to make both js work without window.onload and keep them inside <head>?

  • 4
    Put your ` – Jeremy Thille Apr 22 '21 at 11:30
  • If the first comment did not help: please share more details – Nico Haase Apr 22 '21 at 11:37
  • The mentioned duplicate also has a way to keep using `window.onload`, instead of replacing it with `addEventListener`, if you really want to do it that way. https://stackoverflow.com/a/16683336/1427878 – CBroe Apr 22 '21 at 11:42

1 Answers1

1

onload, as you have noticed, can only hold a single event handler. When you assign a new one, any existing one is overwritten.

Instead, use addEventListener(), which, as the name already says, adds a listener when called.

So instead of

window.onload = function () { ... };

just do

window.addEventListener('load', function() { ... });

Please note that the load event might not be the optimal lifecycle hook in your case. load comes after DOMContentLoaded, and load waits until all external assets like images, stylesheets, fonts etc are loaded.

More often than that what you really want is to make sure to wait until all the DOM elements are readily parsed and available. For that purpose, the DOM API has the DOMContentLoaded event:

window.addEventListener('DOMContentLoaded', function() { ... });

Instead of working with listeners like this, you also have two other options:

  1. Either place your <script> tag right before the closing </body> tag:

    <script src="path/to/my.js"></script>
    
  2. Or use the defer attribute on your <script>, which allows to keep <script> inside the <head>:

<head>
  ...
  <script src="path/to/my.js" defer></script>
  ...
</head>
connexo
  • 41,035
  • 12
  • 60
  • 87