Is there any drawback to putting code (which will interact with the DOM, adding event listeners and so on) just before the closing </body> tag?
<!-- all the HTML comes before this -->
(function() {
do_stuff_with_the_DOM();
})();
</body>
It seems to work in my own tests, but I never see this method used in tutorials, code examples, or other people’s projects. Is there a reason not to do it? Are there edge cases that only seem to pop up when you begin using this in production and see many page views across a variety of browsers?
My project doesn’t use jQuery or any other toolkit, and I’m aware of the alternatives that mimic jQuery’s $(document).ready() functionality. Do I really need to use one of those? (It should go without saying, but I’m looking to run the code before window.load.)
Note that the code I want to run (do_stuff_with_the_DOM() in the example above) would be defined in an external script file, if that makes a difference.
You should put your JavaScript code in the place that makes the most sense for what it needs to do. In most cases, you need your js to attach events to DOM objects, which is hard to imagine if those DOM objects don’t exist when the js is running. So putting it at the bottom of the html is a sensible, simple, and common approach. Is it the best? That’s arguable.
Another approach is to attach your JavaScript to the various events that different browsers fire when the DOM is fully loaded. There is nothing wrong with this, although detractors don’t like that it’s often done in a way that requires an additional blocking HTTP request in the
headelement.Event delegation offers a third approach that lets you attach events to parent elements (such as
body) very early, and when appropriate child events exist the events will fire as if they had been attached to those elements all along. It’s a very cool approach with theoretically the best early-loading performance of any of the above, but has pitfalls in that not all events bubble all the way to the top, like you might expect, and that it often tempts you to separate your JavaScript into multiple chunks, which can violate separation of content and behavior.