Google AMP allows the complete functionality of our Javascript integration, including the ability to A|B test against other content recommendations. This integration requires uploading a file to your site's server containing the Widget Code. This includes the HTML structure of the recommendation area, the template for each recommended item, as well as the Javascript for requesting, rendering, and tracking the recommendations. This file will then be used as the source for an iframed section of the page where recommendations will be displayed.


Because recommendations are iframed within the page, you'll also need to make sure your beacon snippet includes the following custom config if you copy your existing widget code from your website:

var customConfig = {
    isInIframe: true
}


This tells our Javascript to look at the parent window rather than the iFrame to obtain the current URL context (i.e. what item the user is currently reading or watching).


Widget Code

The code here is a very simplified sample to use as a starting point for your own widget. You will want to customize it with the following:

1) A link to your own CSS file, so that you can use your own classes, styling, and branding.

2) A modified template containing placeholders for all of the fields you will want to display in the recommendations and the CSS classes and styling which should be applied to them. By default we will return the URL, title, and image for the item. You can use $p("setRequestFields") to include any additional fields available for your inventory items. (See this article for more information on returning additional fields).

3) Your own account's JS key. The key included in the sample below (f7tsbsle43k5irci) is for demonstration only.


<html>
  <head>
    <link type="text/css" rel="stylesheet" href="https://domain.com/path/to/yourCSSfile.css" media="all" />  <!-- REPLACE URL -->
  </head>
  <body>

<!-- Baseline Section -->
  <!-- This section acts as a skeleton for the recommendations from LiftIgniter. It can be static placeholder content, empty divs, or other dynamically generated content, such as recent posts in chronological order. It will be overwritten by the LiftIgniter Javascript $p("render") function according to the Template defined below. -->
        <div id="li-recommended-unit">
              <div class='li-widget-item recommended_item '>
                <a class='headline' href='//url-1'>Title 1</a>
              </div>
              <div class='li-widget-item recommended_item '>
                <a class='headline' href='//url-2'>Title 2</a>
              </div>
              <div class='li-widget-item recommended_item '>
                <a class='headline' href='//url-3'>Title 3</a>
              </div>
              <div class='li-widget-item recommended_item '>
                <a class='headline' href='//url-4'>Title 4</a>
              </div>
              <div class='li-widget-item recommended_item '>
                <a class='headline' href='//url-4'>Title 4</a>
              </div>
            </ul>
        </div>

<!-- Widget Template - MODIFY THIS -->
  <!-- The template controls how the recommendations will be displayed. You can include your own CSS classes and any other styling options you choose. -->
    <script type="application/mustache"
        id="li-recommendation-template">
            <div>
                <a href="{{url}}" target="_new">
                        <img class="img-responsive" src="{{thumbnail}}" alt="{{title}}"></img>
                </a>
              </div>
              <div>
                <h2>
                  <a href="{{url}}" target="_new" title="{{title}}">{{title}}</a>
                </h2>
              <div>
                {{description}}
              </div>                   
    </script>
    
<!-- BEACON SNIPPET START -->
    <!-- The Beacon calls our JS SDK, which allows the usage of the other $p functions seen below. It also applies a first-party tracking cookie to identify unique users. -->
    <script>
if (typeof $igniter_var === 'undefined') {
  // Ensures that our client code is updated.
  (function(w, d, s, p, v, e, r) {
    w.$ps = (w.performance && w.performance.now && typeof(w.performance.now) == "function") ? w.performance.now() : undefined;
    w['$igniter_var'] = v;
    w[v] = w[v] || function() {
      (w[v].q = w[v].q || []).push(
        arguments)
    };
    w[v].l = 1 * new Date();
    e = d.createElement(s), r = d.getElementsByTagName(s)[0];
    e.async = 1;
    e.src = p + '?ts=' + (+new Date() / 3600000 | 0);
    r.parentNode.insertBefore(e, r)
  })(window, document, 'script', '//cdn.petametrics.com/YOUR_JAVASCRIPT_KEY.js', '$p');
            // If you have a LiftIgniter account, you can replace "YOUR_JAVASCRIPT_KEY" with your own JS key to get recommendations from your own inventory. Make sure to replace it in the URL above, and in the $p("init") function below.

var customConfig = {
    isInIframe: true
}

$p("init", "YOUR_JAVASCRIPT_KEY", customConfig)
        }
        //---------- BEACON SNIPPET END------------
        //---------- WIDGET CODE START------------
        //-- 1. Define Rendering Area --
        //$p('render') uses the Template defined in the HTML above to overwrite the Recommendation Area with the items recommended by LiftIgniter.f
        var rendering_callback = function (resp) {
            var els = document.querySelectorAll('#li-recommended-unit div.li-widget-item');
            var template = document.querySelector('#li-recommendation-template').innerHTML;
            for (var i = 0; i < resp.items.length; i++) {
                els[i].innerHTML = $p('render', template, resp.items[i]);
            }
        }
        //-- 2. Define Items to be Tracked --
        //$p('track') attaches event listeners and query string parameters to each href in the recommendation area.
        var trackAlgo = function (algorithm) {
            $p('track', {
                elements: document.querySelectorAll('#li-recommended-unit div.li-widget-item'),
                //make sure that the "name" value selected here matches the value of "widget" in the $p("register") function. This allows us to match recommendation requests to the widget activity reported in our dashboard. You can use any URL-safe value for the name.
                name: 'amp-pages',
                source: algorithm
            });
        }
        //-------- SWITCHING BASE AND LI RECOMMENDATIONS IN THIS FIDDLE ------------
        // To switch between showing base and LI recommendations, change the > or < sign in line 115 to the opposite, then Run the fiddle again.
        var abTestHandler = function(slice) {
          // Slice is modulo 100 of the cookie hash. 100 = 100% of traffic will see LI recommendations. 50 = 50% of traffic will see LI recommendations
          if (slice < 100) {
            // Register call to overwrite widget being tested with LI recommendations,
            // and track metrics appropriately.
            $p('register', {
              max: 5,
              widget: 'amp-pages',
              callback: function(resp) {
                // You might wish to wrap the code in this callback inside jQuery, to handle load order issues
                // Trigger rendering once recommendations are returned
                rendering_callback(resp);
                // track the source of the recommendations as 'LI' because they were recommended by LiftIgniter.
                trackAlgo('LI');
              }
            });
          } else {
            // track the source of the recommendations as 'base' for the control slice of the A|B test.
            trackAlgo('base');
          }
          // Executes $p("register") and all arguments to get the recommendations.
          $p("setRequestFields",["name","title","url", "thumbnail" ,"description", "author"])
          $p('fetch');
        }
        // Decide which slice the current user is on.
        // $p('userHash') hashes user cookie id to a random 32-bit integer.
        // $p('abTestSlice') returns the absolute value of this number mod 100
        $p('abTestSlice', {
          callback: abTestHandler
        });
        //---------- WIDGET CODE END------------
    </script>
</body>
</html>


AMP Display Code

Within your AMP page, you'll create an amp-iframe section to house the widget code file you uploaded to your server. Simply replace the "src" value in the example below with the link to the file created in the previous step, and you should see the recommended items appear.


<amp-iframe width=300 height=900
    allowfullscreen
    sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"
    layout="responsive"
    frameborder="0"
    src="https://linkto.yourdomain.com/widget-code-file.html"> //REPLACE URL
</amp-iframe>