Specifically: friendbuy referral program; Generally: adding scripts to <head> tag (DocHead, inject-initial packages)

Ok, so I am struggling to integrate friendbuy.com referrals into my meteor app on a number of fronts. This seems like something that should be oh so simple but it doesn’t seem to be. There are 2 parts to the integration:

  1. SmartPixel script to go in the head of every page
  2. Conversion Tracker script to go only on the order confirmation page

The packages I have been looking at using are:

  • meteorhacks:inject-initial
  • kadira:dochead
  • or JQuery/JS to append the script

Let me start with 1. Smart Pixel:

I used inject-initial to add the script to the head tag across the whole app:

  if (Meteor.isServer){
         Inject.rawModHtml('inject a script at the beginning of the head', function(html) {
              return html.replace('<head>', '<head><script>friendbuy-script-here</script>');
         });
    }

This works fine for static script but I need to be able to add things like userId to the script but I am struggling to figure out how to access this information outside of methods/pubs and add it to the script - So that’s my first question - how do I do that?

Of course I could just paste the script directly into the head tag - but again, how do I add dynamic variables?

In relation to 2. Conversion Tracker:
This needs to feature on only 1 page, namely the order confirmation page. What is the best way to get a script to appear only in the head tag of one page. I have been playing around with trying to add it when the order is confirmed and remove it when I navigate away from that page. Are there any suggestions around this?

I am really pulling my hair out over this (and I haven’t got much to begin with) so any help is appreciated!

Thanks,

Brian

In general, my approach is as follows, if you are using Blaze. Not sure how it would translate to React, etc.

Static scripts that are required site-wide go in the /client/compatibility folder.

Static scripts that are required on a per-template basis go in the onCreated function of that template, either as-is, or as an import.

External scripts that are required site-wide go in a Meteor.startup function on the client, using $.getScript.

External scripts that are required on a per-template basis go in the onCreated function of that template, using $.getScript.

$.getScript takes a callback, which allows you to set things like reactiveVars that you can access in your template to wait until that script is loaded.

Template.myTemplate.onCreated(function () {
  const self = this;
  self.readyVar = new ReactiveVar(false);
  $.getScript('https://somescript.js', function () {
    cosole.log('Script loaded!');
    self.readyVar.set(true);
  });
});

Template.myTemplate.helpers({
  ready () {
    return Template.instance().readyVar.get();
  },
});
<template name="myTemplate">
  {{#if ready}}
   <!-- your content that relies on that script -->
  {{/if}}
</template>