0

Javascript loading before the page?

I am working on some stuff in code playground html/css/js and I noticed that I had an issue of a javascript variable initializing to NULL and then failing when I tried to call functions on it. I used a workaround of using <script></script> at the end of the page to force the javascript to load after the body is finished. But there should be a better work around for it. Does anyone have any idea of how to get around this?

5th Jun 2017, 8:11 PM
caleb
caleb - avatar
4 odpowiedzi
+ 6
in your JS tab: option 1) window.onload=function(){ // your code here } option 2) // variables that will hold reference to HTML elements var myButton = null; function init(){ // get required HTML elements myButton = document.getElementById("btn1"); } // functions that control your program function foo(){ // do something or something else } // call the init() function once the HTML page is loaded window.onload = init;
5th Jun 2017, 8:31 PM
Burey
Burey - avatar
+ 5
mind posting the problematic code?
5th Jun 2017, 9:41 PM
Burey
Burey - avatar
+ 1
Nvm that works perfectly. Idk why it was giving me that error a little while ago! Thanks for the help! Option 1 is the one I'm using in case anyone else has the same problem
5th Jun 2017, 10:01 PM
caleb
caleb - avatar
0
Neither of those approaches worked for me. For some reason I get the result of window.onload being undefined.
5th Jun 2017, 9:37 PM
caleb
caleb - avatar