Google’s John Mueller says that you should put JavaScript code under the HTML header so that search engines can understand it.
The short answer is yes; if the HTML code is not near the top of the page, it may negatively affect your SEO efforts .
More precisely, it’s crucial to maintain the HTML document’s section at the beginning of the page. The details Google requires to fully read your website should be in this area.
JavaScript script should always be inserted after the HTML headers.
Mueller advises making use of Search Console’s rendering tool to make sure that JavaScript isn’t interfering with the section.
According to Mueller, the location of the primary content is less critical than how well-organized and clean the section is in order for Googlebot to comprehend it.
For the content, it doesn’t matter as much, but the head material really needs to be neat on top since it’s for machine-readable information that’s validated to be in a specific portion of the page.
Put an end to JavaScript! (At the top)
When creating a website, it is recommended to place the JavaScript code close to the closing element at the bottom of the HTML text.
This is because JavaScript can cause a website’s rendering to be delayed as it loads, which will negatively affect the user experience.
The HTML can be presented first by putting the JavaScript near the bottom of the page, allowing the user to read the content while the JavaScript loads in the background.
The async or defer properties can also be used to stop external JavaScript files from obstructing the page’s rendering.
Source: Search Engine Journal