'Rails insert automatically my code into body tag not into head tag

I did it in application.html.erb

<html>
  <head>

     <%if @hasAdsense == true%>
     <script data-ad-client="ca-pub-64xxxxxxxxxxx" async 
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
     <%end%>
  
  </head>

  <body>
     <%= yield %>
  </body>
</html>

but when I see a page with chrome developer tools ,it's automtically inserted in body not in head.

so html code of page where @hasAdsense==true looks like this.

<html>
  <head>
  </head>

  <body>
      <script data-ad-client="ca-pub-64xxxxxxxxxxx" 
      async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  </body>
</html>

I don't know why this happens, but google bot inspect Adsense script in head tag, so I think this can cause problem so that I can't use Adsense script in my website.

is there a way let rails not insert automatically adsense script into body tag?



Solution 1:[1]

do you have

<%if @hasAdsense == true%>
     <script data-ad-client="ca-pub-64xxxxxxxxxxx" async 
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<%end%>

in any other views, because it might come from the yield.

We probs need a little more info here, is @hasAdsense a boolean value (can you confirm by showing your controller or checking on the page directly)? does this happen with other content? so if you made a if statement with <title>Hello World</title> does that render in the body as well?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haumer