+ 8

What to do if we want to put some of JS in our HTML head part and some in our body part...[Specially in this sololearn app]

Pls explain with example if possible ...

27th Feb 2019, 11:15 AM
Shourya
Shourya - avatar
6 ответов
+ 8
Aησηүмσυs That's not good practice. Never use JavaScript in your head section. Because Everytime you run your code, it will run head part first. Now you're manipulating DOM with JavaScript which is on your head. That DOM Will be not available which will cause an error. Everytime use JavaScript in body because it will load all elements first and then JavaScript. But if you still want to do that you can include script at both places.
27th Feb 2019, 11:45 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 4
The one in the head is read first. Then the one in the body. If JS done at the end of html, it doesn't block the rendering of html/css while the JS is downloaded and rendered by the browser.
27th Feb 2019, 11:22 AM
wenz
wenz - avatar
+ 2
Wenz is correct. Javascript can be placed in the head or the body. Read about it at https://www.w3schools.com/js/js_whereto.asp. They don’t really explain why you would do one or the other, so I will do that. Javascript might be a function to call later, or it might be code to actually do when it gets read. Where to put javascript is a case by case situation. If you have a function that will be called automatically when a page is loading, that function needs to be declared before it is run. It can be in the body before where it gets called, or in the head. Now if you were to have something like: <body onload=“somefunction();”> to call somefunction when the body loads, that function will have to be in the head. If you have a function that will be called by a user action after page load, that function can go anywhere, and is generally put at the end of the body. Unless it’s a large chunk of code, placement won’t affect page load speed, but at the end of a page is still good for organization. What if it’s not a function, but code that’s executed as it’s read, like using javascript to actually print something to the page? Obviously that has to be placed where you want it to go. eg: <script>document.write(Date());</script> would display the current date exactly where the code is in the page.
27th Feb 2019, 2:03 PM
Mike
Mike - avatar
+ 2
You can place your script either on the head or body element, but you should stick to one of them instead of having two different scripts
28th Feb 2019, 3:00 AM
Christian Paez
Christian Paez - avatar
+ 1
but what for?
28th Feb 2019, 9:23 AM
Luka Timofeev
Luka Timofeev - avatar
28th Feb 2019, 11:59 AM
Janning⭐
Janning⭐ - avatar