TLDR: Load Global Function Files first, Then Load Event Handlers
Whenever you are accessing an element within a JS file or <script>
block, it is essential to check to make sure that element exists, i.e., jQuery's $(document).ready()
or plain JS's document.addEventListener('DOMContentLoaded', function(event)...
.
However, the accepted solution does NOT work in the event that you add an event listener for the DOMContentLoaded, which you can easily observe from the comments.
Procedure for Loading Global Function Files First
The solution is as follows:
- Separate the logic of your JS script files so that each file only contains event listeners or global, independent functions.
- Load the JS script files with the global, independent functions first.
- Load the JS script files with event listeners second. Unlike the other previous files, make sure to wrap your code in
document.addEventListener('DOMContentLoaded', function(event) {...})
. ordocument.Ready()
.