Can't use Segment's tracking snippet in Heex root layout

Here’s the snippet Segment is giving me:

      !function(){var||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"];analytics.factory=function(e){return function(){var;t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="" + key + "/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};analytics._writeKey="rV4X85dnTrGEcrOo7jQ28eoBTTDBJLUB";;analytics.SNIPPET_VERSION="4.15.3";

How can I use this snippet in my root.html.heex template?

It’s not compiling:

== Compilation error in file lib/gaming_web/views/layout_view.ex ==
** (Phoenix.LiveView.HTMLTokenizer.ParseError) lib/gaming_web/templates/layout/root.html.heex:13:676: expected attribute value or expression after =
(phoenix_live_view 0.16.3) lib/phoenix_live_view/html_tokenizer.ex:342: Phoenix.LiveView.HTMLTokenizer.handle_attr_value_begin/5

To solve this I moved the snippet to app.js however this isn’t a good fix.

I fixed it by formatting the code, and changing one line:
for (var e = 0; e < analytics.methods.length; e++) {
for (var e = 0; analytics.methods.length > e; e++) {

That’s strange - does anyone know why it would fail in one way and work the other way?

That sounds like it might be this issue: (Phoenix.LiveView.HTMLTokenizer.ParseError) expected tag name on JS code · Issue #365 · phoenixframework/phoenix_html · GitHub

Try upgrading Phoenix LoveView to fix it.

1 Like

The formatting solved the issue around the = sign, so I don’t know what that was. The other issue I got, I think was related to it parsing the less-than sign (<) as a tag opening. Reversing it to a greater-than seems to have gotten past the parser. Just a hack.

Like @axelson pointed out - upgrading to latest {:phoenix_live_view, "~> 0.17.6"} (as of today) will fix many html validation issues in heex.