+ 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 ...
6 Antworten
+ 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.
+ 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.
+ 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.
+ 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
+ 1
but what for?
+ 1
People!
We have async and defer!
https://stackoverflow.com/questions/10808109/script-tag-async-defer