How to make js code load after all ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to make js code load after all ?

I have always to write onload = function() { } if I want to writ an get element function And that make me crazy Pleas if there is I solotion for this to make it load in the end by defult

21st May 2020, 10:14 AM
youssef soufiane
youssef soufiane - avatar
7 Answers
+ 4
Better: take the time to write the few characters needed for full form of function declaration rather than ES6 arrow function (not supported in older browsers / devices) and use of addEventListener method to assign event handler (avoid risk of overwrite or being overwrited) ^^ For quick start prototyping I was often lazy and just type: onload = ()=>{ // all my code (give the advantage to avoid global variables) }; ... but each time a project grows, and each time I want to run my code in older browsers/devices I was annonying to replace it at least (it's rare that I use external libraries wich could overwrite or being overwrited by my own onload handler) by: onload = function() { // ... }; So I've got and kept habit to use it as soon I start code. However, if compatibility with other devices than yours is not a concern, and risk of overwrite is measured, you could simply write (or cut-paste) your js in the html tab at end of the <body></body> content, wrapped inside a <script><</script> element ;P
21st May 2020, 11:17 PM
visph
visph - avatar
+ 3
Arrow function aren't "better", just "shorter" ;) If you want "better" behavior, rather add "use strict" at start of function body, and use a named function rather than anonymous (wich are necessarly arrow function) for easiest debugging using stack trace ^^ (give names to function even if not required are also now part of my anti-lazy habits with advantage to be self descriptive code ;P)
21st May 2020, 11:50 PM
visph
visph - avatar
+ 2
you could write <script> at end of <body> and leave js tab empty ;) (but that seems to me less comfortable than using js tab and type the few characters required to wrap js code in onload function handler ^^)
22nd May 2020, 12:09 AM
visph
visph - avatar
+ 1
"Teorical programmer" doesn't have to debug code, wich I often do :P
22nd May 2020, 12:03 AM
visph
visph - avatar
0
Guys All I'm talking about is coding in solo learn and not other editors becaus I code only on my phone that's why And here I can't write script tags in the end bcz they exist by defult I hope u andersand my meaning
22nd May 2020, 12:07 AM
youssef soufiane
youssef soufiane - avatar
0
Thank you 👍
22nd May 2020, 12:11 AM
youssef soufiane
youssef soufiane - avatar
0
You could always just use an iife (()=>{ //code })() remember to put <script> at the bottom
22nd May 2020, 10:26 PM
Logomonic Learning
Logomonic Learning - avatar