TarjeiB
3/11/2018 - 1:38 PM

Prefetching AMP pages that are within 50% of the viewport.

Prefetching AMP pages that are within 50% of the viewport.

// src: https://youtu.be/0BxYYMNit7M?t=1785
var io = new IntersectionObserver((intersections) => {
  intersections.forEach((entry) => {
    if(intersection.intersectionRatio > 0.5){
      var a = intersection.target;
      
      var url = a.origin + a.pathname + a.search;
      if(this.haveAmpForUrl(url)){
        url = this.convertCanonicalUrlToAmp(url);
        
        console.log('Adding prefetch <link> for: ' + url);
        var link = document.createElement('link');
        link.setAttribute('rel', 'prefetch');
        link.setAttribute('href', url);
        document.head.appendChild(link);
      }
    }
  });
}, options);