Quantcast
Channel: User HoldOffHunger - Stack Overflow
Viewing all articles
Browse latest Browse all 55

Answer by HoldOffHunger for Calling a JavaScript function in another js file

$
0
0

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) {...}). or document.Ready().

Viewing all articles
Browse latest Browse all 55

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>