js into the js tab or into a script tag? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

js into the js tab or into a script tag?

hello, y have here two shoping cart in js, exactly the sames but: the first has the javascript into the js tab, the second has the javascript int an <script> tag into the html tab. why is the second one working and not the first one? https://code.sololearn.com/Wzw9VdQ91jDS/#js https://code.sololearn.com/W3v89ZEiAcBf/#html

25th Feb 2020, 2:59 PM
Gann
Gann - avatar
3 Answers
+ 4
Javascript code in JS tab (first code) is executed before the document is fully loaded. This triggers error because you are referencing an element that doesn't yet exist, browser has not finished rendering the content. Javascript in the second code works because the script block is placed after the body content, so the elements are there, ready for you to use : )
25th Feb 2020, 3:27 PM
Ipang
+ 3
Hi! Please, try to put your code inside this (in js section): window.onload = () => { // insert all of your code here }
25th Feb 2020, 3:30 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
you are all awsome, thanks :)
25th Feb 2020, 6:02 PM
Gann
Gann - avatar