0

It seems the following inline code works by putting js right after the tag:

   (1) 
   <div id="xx"></div>
    <script>
          document.getElementById('xx').addEventListener('click', aFunction);
    </script>

It seems there is no need to wait document ready like this:

    (2)
    <div id="xx"></div>
     <script>
    document.addEventListener("DOMContentLoaded", function() {
         document.getElementById('xx').addEventListener('click', aFunction);
    });
    </script>

Will the inline code (1) always work?

Please notice that I made sure <div id="xx"></div> is before the script.

Bruce
  • 95
  • 7
  • You should wait till the document is loaded otherwise you will be finding an element named xx which is not yet loaded – Arpit Solanki Feb 26 '18 at 14:07
  • good practice, thats how you want your page working. – Gerardo BLANCO Feb 26 '18 at 14:07
  • `there is no need to wait document ready` - As it is impossible to attach events to elements directly which are not in the DOM (ignoring deferred binding) when do you think `DOMContentLoaded` executes! ? Please see [**Documentation on DOMContentLoaded**](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) for details. `The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes` So if you want to interact with images you might have issues. #RTM – Nope Feb 26 '18 at 14:09
  • 1
    You don't _have to_ wait. You only have to be sure that every element you're going to modify is available in the DOM when the modifying script is executed. – Andreas Feb 26 '18 at 14:09
  • Saw these related questions, possible duplicate https://stackoverflow.com/questions/5739853/is-it-really-necessary-to-wait-for-dom-ready-to-manipulate-the-dom?rq=1 https://stackoverflow.com/questions/1222849/is-it-ok-to-manipulate-dom-before-ready-state?noredirect=1&lq=1 – kingdaro Feb 26 '18 at 14:14
  • When you place your ` – zer00ne Feb 26 '18 at 14:14

1 Answers1

-2

You dont have to but you should. If you dont you will get errors when you try performing actions on elements in the dom when they havent been loaded yet, using document ready just ensures you dont have this issue, one less problem to debug basically.

Davidola36
  • 12
  • 2