Magento2: Google Analytics code being placed in body instead of head

Created on 9 Mar 2017  路  28Comments  路  Source: magento/magento2

Preconditions


  1. Magento version 2.1.5
  2. Google Analytics Account

Steps to reproduce

  1. Enable Google Analytics in Magento by going to Stores->Configuration->Sales->Google API
  2. Add your Google Account Number and Save

Expected result

  1. The Google Analytics code should be output neat the top the the tag on the page

Actual result

  1. The Google Analytics code is output near the top of the tag

Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/

distributed-cd Fixed in 2.2.x Fixed in 2.3.x Confirmed Format is valid Ready for Work Reproduced on 2.1.x Reproduced on 2.2.x Reproduced on 2.3.x

Most helpful comment

@m7ble83 @korostii from the presentation I read recently we should use reactions to make issues more visible to Magento crew ;)

All 28 comments

This is disputable, actually. If you try to dig any deeper, you'll quickly find out the following:

In practice, the Google Analytics code will work regardless of where you put it on the page. We recommend inserting it in the <head> section or after the opening <body> tag if possible.

https://groups.google.com/forum/#!topic/digital-analytics-fundamentals/V9z4TVXQW_4

So it's quite fine either way as long as the GA code is high in the page.

@korostii It's not actually disputable. One way is correct, the other is not. The fact that it will still function if you do it wrong does not make it correct. The forum post you reference is also 4 years old and the approved method of installation has changed in that time.

@mombrea do you even understand how GA works? Close this senseless ticket and get outta here!

@developer-lindner I sure do understand how it works. Your garbage attitude is a good view into why the Magento 2 code base is so terrible.

Well, "approved" isn't exactly the same as "correct", now is it?
I would argue that this is exactly the case of "good enough", and last time I checked, 90% of Web was built using "good enough" code.

I am not saying this issue isn't worth looking at, I'm just saying that since "it will still function if you do it wrong" (using your own words) I'd rather suggest investing time and effort in stuff which is outright not working at all. And Magento2 has plenty of those, too. If this issue has high priority for you personally, I'd suggest that you either submit a pull request with the change requested in order to speed it up or use a local workaround inside your project (see below).

That being said, I would like to provide technical information I have regarding the code in question: I successfully reproduced the issue in question (no matter whether it should be considered a bug or intended behavior) on Magento 2.1.3 CE.
The code doing it is located here. Thus you can probably make a simple <move> somewhere in your custom layout XML file in order to place it into the <head>.
Important note: Magento 1.9 CE was placing ga.phtml inside the <head> , so there might be a legitimate reason for moving it down into body in 2.x that we just don't know about.

Expected result
The Google Analytics code should be rendered near the top of the <head> tag on the page (at least, inside the <head> tag)

Actual result
The Google Analytics code is rendered near the top of the <body> tag (inside the <body> tag)

@korostii thanks for the added info. Yes, 100% agree that this is not critical, but I noticed it and reported the issue.

The code should be added near the top of the <head> tag and before any other script or CSS tags

I don't see how such simple sentence could be misinterpreted. Any forum topic from 2013 is not an argument, you know :)

Not following GA recommendations could lead to decrease of some SEO metrics, like PageRank.

It has been already a week that GA is not working anymore. Today we figured out the problem is exactly the way GA code is placed as it works wrong against common js deferring practices.

You should consider to fix this point asap

@lucafabbri do you mean that Google became strict about that? :O

Sorry to reignite the issue again but I've come across this issue today. @mombrea is correct and the error is even highlighted in Google WMT when you try to verify ownership through analytics.

Has it been four months already? Unbelievable.
It would be nice to see some official response from @magento-team, for a difference.

@m7ble83 @korostii from the presentation I read recently we should use reactions to make issues more visible to Magento crew ;)

I confirm that Google has become strict about the position of that script. Now it is an important issue for Analytics.

I have also confirmed GA will not recognize analytics if the script is not in the tag. For now I've moved the position of the script by manually extending the GA module (https://magento.stackexchange.com/a/176032/51425).

// Closure. Means that nothing will be passed into the global variables (on window)
(function(i, s, o, g, r, a, m) {

    // Initial declaration of a function queue. This is what will spool the GA events to send if they're triggered
    // further up the page.
    // Find more about the function queue pattern here:
    // https://stackoverflow.com/questions/17528749/semaphore-like-queue-in-javascript/17528961#17528961
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();

    // Creates the script tag. This is what will inject the actual analytics.js script; for the moment. This snippet
    // itself does very little
    a = s.createElement(o),
        m = s.getElementsByTagName(o)[0];

    // Make the script async. This means it doesn't block the rendering of the document; it's basically harmless to
    // page load.
    // See https://developer.mozilla.org/de/docs/Web/HTML/Element/script for details
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga.js uses the function queue pattern, and balances both the declaration of a required global property and the use of async scripts extremely well. In all browsers supported by m2, this will result in ga being available early, but also non-blocking (thanks to the function queue).

Or, TLDR regardless of what the docs say stick it in the head.

References: https://developers.google.com/analytics/devguides/collection/analyticsjs/

Hi @mombrea. Thank you for the report. We are moving your feature request to the special project. You can track this issue here: https://github.com/magento-engcom/community-features/issues/29

Hi @magento-engcom-team, could you please kindly explain why is this treated as a feature request?

I mean, the feature is already in there but it behavior seems imperfect (and even different from Magneto1, for that matter). It probably should be treated as bug, it might be potentially deemed a low-priority "improvement" if you'd say the current behavior is "good enough" and explain why it's done that way.

But it's certainly not a feature request. At least, in my humble opinion.

If you guys happen to have some different criteria, I'd very much like to hearseeread about those in depth. If there are some kind of guidelines in that regard, please do share them.
I think it would be utmost helpful to have some shared understanding among the community about such basic things.

@magento-engcom-team, please check if
https://github.com/magento/magento2/issues/8837#issuecomment-316116839
https://github.com/magento/magento2/issues/8837#issuecomment-330065625
reports are true and if so issue should be treated as a bug and reopened. Otherwise just close it back and treating as improvement/feature request seems correct.

@mombrea, thank you for your report.
We've acknowledged the issue and added to our backlog.

distributed-cd

@KravetsAndriy thank you for joining. Please accept team invitation here and self-assign the issue.

Hi @mombrea. Thank you for your report.
The issue has been fixed in magento/magento2#14293 by @KravetsAndriy in 2.2-develop branch
Related commit(s):

The fix will be available with the upcoming 2.2.5 release.

Hi @magento-engcom-team

This issue was originally reported on 2.1.5, thus I was wondering: are there any plans on backporting the fix to the 2.1.x branch as well? Or is that also totally up to the community now?

Hi @mombrea. Thank you for your report.
The issue has been fixed in magento/magento2#14513 by @rostyslav-hymon in 2.3-develop branch
Related commit(s):

The fix will be available with the upcoming 2.3.0 release.

@korostii it is highly unlikely in general for 2.1.x issues with less than critical/blocker priority considering 2.3.0 regression testing already started. Whenever 2.1.x backport is pretty trivial and somebody really need it, just do it.

Wow, okay, thanks for the information.
BTW, do you know if there's an official End Of Life announced for the 2.1.x branch yet?

@korostii didn't see any announcement yet, if I remember correctly it should be generally 2.3.0 release + SOME REASONABLE PERIOD similar to 2.0.x EOL.

Hi @magento-engcom-team We need the backport for Magento 2.1.x, could you confirm when it should be release

Was this page helpful?
0 / 5 - 0 ratings