TypeError: null is not an object
The lifecycle of an HTML page has three important events:
- DOMContentLoaded - the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures and stylesheets may be not yet loaded.
- load - the browser fully loaded the HTML and also external resources like images and stylesheets.
- unload (beforeunload) – the user is leaving the page.
The DOMContentLoaded event fires when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading . When the browser initially loads HTML and comes across a script area in the text, it can't continue building DOM .
You can do so by adding an event listener to the document object for the DOMContentLoaded event.
The addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called. The DOMContentLoaded event happens on the document object . We must use addEventListener to catch it.
In the following example, we can resolve this type of issues by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.