To continue from this Adding javascript and css libraries for a doctype using custom script - #15 by hari.kishor
This may help What is JavaScript? - Learn web development | MDN
In particular these sections:
What is JavaScript doing on your page?
Script loading strategies
That tutorial should help - for eg you may need to listen for the “DOMContentLoaded” event?
Here’s an intro to events Introduction to events - Learn web development | MDN