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 triggers once the primary HTML document has been entirely loaded and parsed, disregarding the completion of loading for stylesheets, images, and subframes. Upon the browser's initial encounter with HTML, if it encounters a script area within the text, it temporarily halts the process of constructing the DOM until the script's execution is complete. This event is designed to facilitate interactions that necessitate access to the DOM's structural content before the entire page, including external resources, has been fully loaded.
You can do so by adding an event listener to the document object for the DOMContentLoaded event.
The addEventListener() function operates by incorporating a function or an object that implements the EventListener interface into the roster of event listeners designated for the specified event type on the specific EventTarget on which the function is invoked. The occurrence of the DOMContentLoaded event is associated with the document object. To capture and respond to this event, it is imperative to utilize the addEventListener() method.
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.