Javascript: the earliest moment to add an event listener to a document

I want to add a keydown event listener to a document object without jQuery.

In the listener, I do not access the DOM. The only thing I need from the DOM is the document object itself. I want to disable pressing a certain key.

Is it safe to call it directly in the script (I mean when the script loads), or do I need to use the onload callback (or maybe something else)?

Thanks in advance.

+4
source share
3 answers

The document object is always available wherever you place your script. No need to wait for DOMContentLoaded or anything else; just add a listener whenever you want.

This does not apply to document elements.

+4
source

You can just bind to the DOMContentLoaded event. Here's how jQuery does it.

Example:

 document.addEventListener("DOMContentLoaded", function(){ //Bind the key event here. }); 

This does not work in IE. So for IE you can do this:

 document.attachEvent("DOMContentLoaded", function(){ //Bind the key event here. }); 
+3
source
  document.onload = function() { document.onkeydown = function() { // disable key }; } 

can work.

0
source

Source: https://habr.com/ru/post/1399076/


All Articles