Is there a reason to remove the EventListener DOMContentLoaded after the event has been processed?

Like many others, I use:

document.addEventListener('DOMContentLoaded',domLoadedFunc,!1); 

Combined with window.onload to handle events that should fire as soon as the DOM is loaded and parsed.

I was wondering if there is a reason to explicitly remove the DOMContentLoaded listener after it starts.

Something along the lines (inside our domLoadedFunc):

 if(document.removeEventListener){ document.removeEventListener('DOMContentLoaded',domLoadedFunc,!1); } 

Is there any reason to remove the DOMContentLoaded listener after it starts?

+6
source share
1 answer

Once an event has been triggered, it will not fire again. Thus, your code will not have any other result if you delete it or not, as soon as it is fired for the first time.

Technically, if you had many event handlers attached to a document object, it might be a little faster to remove event handlers that are no longer needed, but this is balanced with additional code that you write and execute just to remove it.

Personally, I code thoughts in this sequence of priorities: correctness, reliability, readability, maintainability, simplicity, and then performance, and only do something purely for performance when it is really needed. So, following this hierarchy, I would not delete the event handler because it is not needed for any of the first four priorities, it does not help the simplicity of the code and is not a performance issue that matters.


One of the reasons I saw for deleting an event handler like this is if you have several different events that you control, and after the first run you want to make sure that you are not responding to any of the other events that you are also in control. If you remove other handlers, you do not need to keep a separate flag to keep track of the fact that you have already done your job (for example, if you listened to both DOMContentLoaded and window.onload and just wanted to answer what happened before.


FYI, if you are interested in a simple javascript version of jQuery $(document).ready() , which works in all browsers (uses DOMContentLoaded when available, returns to other means when not), which sounds like you can work above, there is a simple easy-to-use implementation of the docReady() function here: pure JavaScript, equivalent to jQuery $ .ready (), how to call a function when the / dom page is ready for it , with which you can use or copy / learn concepts.

+3
source

All Articles